如何限制postgreSQL中特定列的结果数量?

时间:2010-02-23 13:24:54

标签: sql postgresql

我有一个包含用户项目的表格。每个用户可以具有多种类型的项目,并且可以使每个项目不止一次。我想看看每个用户拥有的每种类型的项目数量。所以我使用以下查询:

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;

所以我得到这样的东西:

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

现在,我想只看到每个用户的前3项。在上面的示例中,对于用户1,我想要查看项目X和Y,对于用户2,我想要查看项目A,B和C.

我怎么能这样呢?

谢谢!

2 个答案:

答案 0 :(得分:3)

使用PARTITION BY。这样的事情应该有效:

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;

答案 1 :(得分:0)

不幸的是,我没有Postgres来测试这个,但是如下所示的查询可以让你得到你想要的结果。

select user_name, item_name, item_count from
(
  select user_name, item_name, count(item_name) as item_count,
    dense_rank() over (order by count(item_name) desc) as item_rank
  from my_table 
  group by user_name, item_name
)
where item_rank <= 3;
相关问题