Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I limit number of results by a specific column in postgreSQL?

Tags:

sql

postgresql

I have a table with user items. Each user may have several types of items, and may have each item more than once. I want to see how many items of each type each user have. So I use the following query:

select user_name, count(item_name) as "count_item", item_name 
from my_table 
group by user_name, item_name 
order by user_name, count_item desc;

So I get something like this:

user_name | count_item  | item_name
----------+-------------+-----------
User 1    | 10          | item X
User 1    | 8           | item Y
User 2    | 15          | item A
User 2    | 13          | item B
User 2    | 7           | item C
User 2    | 2           | item X

etc.

Now, I want to see only the first 3 items of each user. In the above example, for User 1 I want to see item X and Y, and for User 2 I want to see items A, B and C.

How can I acheieve this?

Thanks!

like image 655
Dikla Avatar asked Feb 23 '10 13:02

Dikla


People also ask

How do I limit PostgreSQL results?

The LIMIT clause can be used with the OFFSET clause to skip a specific number of rows before returning the query for the LIMIT clause. Syntax:SELECT * FROM table LIMIT n OFFSET m; Let's analyze the syntax above. The LIMIT clause returns a subset of “n” rows from the query result.

How do I limit a specific column in SQL?

The SQL SELECT LIMIT statement is used to retrieve records from one or more tables in a database and limit the number of records returned based on a limit value. TIP: SELECT LIMIT is not supported in all SQL databases. For databases such as SQL Server or MSAccess, use the SELECT TOP statement to limit your results.

How do I limit the number of results returned in SQL?

The SQL LIMIT clause constrains the number of rows returned by a SELECT statement. For Microsoft databases like SQL Server or MSAccess, you can use the SELECT TOP statement to limit your results, which is Microsoft's proprietary equivalent to the SELECT LIMIT statement.

How do I SELECT a specific column in PostgreSQL?

PostgreSQL SELECT statement syntax If you specify a list of columns, you need to place a comma ( , ) between two columns to separate them. If you want to select data from all the columns of the table, you can use an asterisk ( * ) shorthand instead of specifying all the column names.


1 Answers

Use PARTITION BY. Something like this should work:

select user_name, count_item, item_name 
from (select user_name, count(item_name) as "count_item", item_name 
    row_number() over (partition by user_name order by count_item desc)
    from my_table)
where row_number < 4
group by user_name, item_name 
order by user_name, count_item desc;
like image 122
Rob Avatar answered Nov 05 '22 14:11

Rob