我遇到的问题是每组只获得TOP 2值(组在列中)。
示例:
ID Group Value
1 A 30
2 A 150
3 A 40
4 A 70
5 B 0
6 B 100
7 B 90
我希望我的输出是
ID Group Value
1 A 150
2 A 70
3 B 100
4 B 90
简单地说,对于每个组,我只想要2行具有最高值
答案 0 :(得分:5)
大多数数据库都支持ANSI标准row_number()
功能。您可以将其用作:
select group, value
from (select t.*,
row_number() over (partition by group order by value desc) as seqnum
from t
) t
where seqnum <= 2;
要设置id
,您可以在外部查询中使用row_number()
:
select row_number() over (order by group, value) as id,
group, value
from (select t.*,
row_number() over (partition by group order by value desc) as seqnum
from t
) t
where seqnum <= 2;
但是,更改id
似乎很可疑。
答案 1 :(得分:2)
您可以将CTE
与排名函数ROW_NUMBER()
一起使用。
以下是获取结果的查询。
;WITH cte AS
( SELECT Group, value,
ROW_NUMBER() OVER (PARTITION BY Group ORDER BY value DESC) AS rn
FROM test
)
SELECT Group, value FROM cte
WHERE rn <= 2
ORDER BY value