SQL 服务器自定义排序,同时按最大总和分组

SQL Server custom sort while grouping by max sum

我有 3 列 (Year, Number, SUM(Amount)),我正在尝试按最大总和对它们进行排序。

SELECT TOP 1000 
    YEAR(period) AS [Year], id_number, 
    SUM(ISNULL(amount, 0)) AS [Amount]
FROM 
    table
WHERE 
    (YEAR(period) >= 2010 AND YEAR(period) < 2021)
GROUP BY 
    YEAR(period), id_number
ORDER BY 
    SUM(ISNULL(amount, 0)) DESC, id_number, YEAR

这不是我要实现的排序。我想按 id_number 将它们组合在一起,但按返回的所有年份的最大数量排序。我猜我可能必须写一个案例陈述,但我还没有弄清楚。如果我这样做,我会更新。在我为此花费数小时的时间之前,我也想寻求帮助。

非常感谢您。

我想这对你来说应该足够了。只需将它包装在一个子查询中就可以了

SELECT * 
FROM 
    (
        SELECT TOP 1000 
            YEAR(period) AS [Year], id_number, 
            SUM(ISNULL(amount, 0)) AS [Amount]
        FROM 
            table
        WHERE 
            (YEAR(period) >= 2010 AND YEAR(period) < 2021)
        GROUP BY 
            YEAR(period), id_number
    ) x
ORDER BY 
    MAX(ISNULL(amount, 0)) DESC, id_number, YEAR

您可以按索引引用列,例如:

SELECT TOP 1000 
    YEAR(period) AS [Year], id_number, 
    SUM(ISNULL(amount, 0)) AS [Amount]
FROM 
    table
WHERE 
    (YEAR(period) >= 2010 AND YEAR(period) < 2021)
GROUP BY 
    YEAR(period), id_number
ORDER BY 
    3 DESC, id_number, YEAR

非常感谢@Doug,我要运行 下来试试看。 我还提出了一个可能有点疯狂但有效的解决方案。哈哈

SELECT t2.row, YEAR(period) AS [Year], t1.id_number, SUM(ISNULL(amount,0)) AS [Consumption]
FROM table t1 JOIN 
(SELECT id_number, ROW_NUMBER() over (order by SUM(ISNULL(amount,0))desc) as row
FROM table
WHERE (YEAR(period) >= 2010 AND YEAR(period) < 2021)
GROUP BY id_number) t2 ON t1.id_number = t2.id_number
WHERE (YEAR(period) >= 2010 AND YEAR(period) < 2021)
GROUP BY t2.row, YEAR(period), t1.id_number
ORDER BY t2.row, year

@Larnu,我会考虑解决这个问题。谢谢。

根据您的描述,您希望按 任何年份 中的最大总和对 ids 进行排序。如果是这种情况,请在 ORDER BY:

中使用 window 函数
SELECT TOP 1000 YEAR(period) AS [Year], id_number, 
       SUM(ISNULL(amount, 0)) AS [Amount]
FROM table
WHERE YEAR(period) >= 2010 AND YEAR(period) < 2021
GROUP BY YEAR(period), id_number
ORDER BY MAX(SUM(ISNULL(amount, 0))) OVER (PARTITION BY id_number),
         id_number, YEAR;

需要第二个排序键,以便给定 id_number() 的所有行都在一起。