如何根据特定列值跨多行进行选择。例如我有这样的结构
+--+----+-----+
|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 |
+--+----+-----+
我想从每个 ID 中选择三个——基于 count
列中最高值的“前”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 执行此操作?
最佳答案
您应该能够实现 windowing function像 row_number()
获取每个 id
的前 3 名:
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";
关于sql - 根据计数列中的最高值为每个 ID 选择 3 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20888608/