I realize this is likely to be an easy one, but my SQL is basic at best.
Lets say I have a table containing a list of orders, with item_id
being one of the columns. I need to display the 3 least (or 3 most) popular orders of item.
I know that I need to group the orders using item_id
and then count them. Then I need to display the bottom (or top) 3 in descending (or ascending) order. I'm just not entirely sure how to construct a query like that.
To count the number of rows, use the id column which stores unique values (in our example we use COUNT(id) ). Next, use the GROUP BY clause to group records according to columns (the GROUP BY category above). After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause.
With the help of the SQL count statement, you can get the number of records stored in a table.
The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.
In Sql Server:
SELECT TOP 3 item_id, COUNT(*) as itemcount
FROM table
GROUP BY item_id ORDER BY itemcount
And add DESC to order descent
select item_id, count(*)
from table
group by item_id;
will give you the whole list.
Bottom 3:
select item_id
from (
select item_id, count(*) as cnt
from table
group by item_id
order by cnt
) where rownum < 4;
Top 3:
select item_id
from (
select item_id, count(*) as cnt
from table
group by item_id
order by cnt desc
) where rownum < 4;
NOTE: this sytnax is for Oracle. Use LIMIT if you have MySql or TOP if you have sql-server.
ORDER BY will sort your results. Ascending order is default, so use 'desc' if you want to get the biggest.
GROUP BY (when used with count(*)) will count groups of similar objects
where rownum < 4: This is oracles was of doing a LIMIT. It returns the first 3 rows of the query that has been run. Where clauses are run before order clauses, so that is why you have to do this as a nested query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With