[英]How can I limit number of results by a specific column in 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.
我怎么能這樣呢?
謝謝!
使用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;
不幸的是,我沒有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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.