2010-02-23 102 views
11

我有一個用戶項目表。每個用戶可能有多種類型的項目,並且每個項目可能有多個項目。我想查看每個用戶每種類型有多少項。所以我用下面的查詢:如何限制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.

我該如何看待這個?

謝謝!

+4

+1用於詢問數據示例和預期結果! – 2010-02-23 13:26:20

回答

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; 
+0

實際上它應該是由user_name分區 謝謝!! – Dikla 2010-02-23 21:25:48

+0

哎呀!感謝您指出這一點,現在修復。 – Rob 2010-02-23 21:49:39

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; 
+0

無論使用者名稱如何,這會給我最高計數的項目。 :-( – Dikla 2010-02-23 21:27:22