根据计数列中的顶部值为每个ID选择3个值

时间:2014-01-02 17:44:40

标签: sql postgresql

如何根据特定列值选择多行。例如,我有一个像这样的结构

+--+----+-----+
|id|data|count|
+--+----+-----+
|1 |text|30   |
+--+----+-----+
|1 |text|1    |
+--+----+-----+
|1 |text|25   |
+--+----+-----+
|1 |text|12   |
+--+----+-----+
|1 |text|50   |
+--+----+-----+
|2 |text|5    |
+--+----+-----+
|2 |text|2    |
+--+----+-----+
|2 |text|100  |
+--+----+-----+
|2 |text|50   |
+--+----+-----+
|2 |text|1000 |
+--+----+-----+
|3 |text|2    |
+--+----+-----+
|3 |text|4    |
+--+----+-----+
|3 |text|6    |
+--+----+-----+
|3 |text|8    |
+--+----+-----+

我想根据count列中的最高值选择每个ID中的三个 - “顶部”3,这样我最终会得到:

+--+----+-----+
|id|data|count|
+--+----+-----+
|1 |text|30   |
+--+----+-----+
|1 |text|25   |
+--+----+-----+
|1 |text|50   |
+--+----+-----+
|2 |text|100  |
+--+----+-----+
|2 |text|50   |
+--+----+-----+
|2 |text|1000 |
+--+----+-----+
|3 |text|4    |
+--+----+-----+
|3 |text|6    |
+--+----+-----+
|3 |text|8    |
+--+----+-----+

我基本上坚持第一个WHERE子句:我不希望count高于特定值的行,因为它可以返回3个以上的结果。我可以做一个限制3并按计数排序,但这只适用于一个id。如何为表格中的每个不同ID执行此操作?

3 个答案:

答案 0 :(得分:3)

您应该能够row_number() id来实现每个select id, data, "count" from ( select id, data, "count", row_number() over(partition by id order by "count" desc) seq from yourtable ) d where seq <= 3 order by id, "count"; 的前3名:

{{1}}

请参阅windowing function

答案 1 :(得分:1)

SELECT "id",data,"count"
FROM  
  (SELECT "id",data,"count" rank() OVER (partition by "id" ORDER BY "count" DESC) as rn 
  FROM 
  your_table) t
WHERE  rn <= 3
ORDER BY "id","count" desc

答案 2 :(得分:1)

您可以使用PARTITION BY和RANK()函数。 See here