Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count groups of rows and display the top/bottom 3

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.

like image 996
user271132 Avatar asked Feb 19 '10 17:02

user271132


People also ask

How do I count rows in a GROUP BY?

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.

Can you list the ways to get the count of records in a table?

With the help of the SQL count statement, you can get the number of records stored in a table.

Which command is used to count the number of rows?

The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.


2 Answers

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

like image 126
David Espart Avatar answered Nov 03 '22 23:11

David Espart


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.

like image 41
David Oneill Avatar answered Nov 03 '22 21:11

David Oneill