鉴于以下数据,我想要列A的唯一值,但我只想要具有B列最大值的记录。
id | A | B
-------------
1 | 'w' | 1
2 | 'x' | 0
3 | 'y' | 0
4 | 'z' | 0
5 | 'w' | 2
6 | 'w' | 1
7 | 'w' | 0
因此,这种查询的预期结果是:
id | A | B
-------------
2 | 'x' | 0
3 | 'y' | 0
4 | 'z' | 0
5 | 'w' | 2
有什么想法吗?
答案 0 :(得分:2)
使用ROW_NUMBER:
WITH CTE AS(
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY A ORDER BY B DESC)
FROM YourTable
)
SELECT
id, A, B
FROM CTE
WHERE RN = 1
ORDER BY ID
答案 1 :(得分:2)
实际上您需要max(B)
group by A
,我将其命名为 INNER GROUPING BY ,您可以使用特定的self join
来实现此类分组:< / p>
select t1.id,t1.A,t1.B
from table_name t1
join (select A,max(B)B
from table_name
group by A)t2
on t1.A=t2.A and t1.B=t2.B
order by t1.id
结果:
id | A | B
-------------
2 | 'x' | 0
3 | 'y' | 0
4 | 'z' | 0
5 | 'w' | 2