答案 0 :(得分:0)
这是一个经典的limit-per-group问题,可以使用公用表表达式和row_number()
轻松解决。
首先,创建并填充示例表(请在您将来的问题中为我们保存此步骤)
DECLARE @T as TABLE
(
Number int,
Letter char(1),
Volume int
);
INSERT INTO @T (Number, Letter, Volume) VALUES
(1,'A',230),
(1,'B',534),
(1,'C',23),
(1,'D',42),
(2,'D',566),
(2,'E',24),
(2,'F',566);
-- you can add more records but this should be enough for this demonstration
然后,使用带有row_number()
和max(...) over...
的公用表表达式进行分组并按以下顺序排序:
WITH CTE AS
(
SELECT Number,
Letter,
Volume,
ROW_NUMBER() OVER(PARTITION BY Number ORDER BY Volume DESC) As rn,
MAX(Volume) OVER(PARTITION BY Number) As MaxVolume,
FROM @T
)
查询:
SELECT Number, Letter, Volume
FROM @T
WHERE rn <= 2
ORDER BY MaxVolume DESC
结果:
Number Letter Volume
2 D 566
2 F 566
1 B 534
1 A 230