顶级T-SQL

时间:2019-07-16 14:18:52

标签: sql-server tsql sql-order-by items

在上面,我想将第一个数据集转换为后者。目标是按最大音量对数字排序,然后在这些数字中按音量降序选择前2个字母。 T-SQL有什么解决方案吗?谢谢!

enter image description here enter image description here

1 个答案:

答案 0 :(得分:0)

这是一个经典的问题,可以使用公用表表达式和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

You can see a live demo on rextester.