I have 3 columns (Year, Number, SUM(Amount)
) and I am trying to sort them by the max sum of 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
This is not the sorting I'm trying to achieve. I'd like to group them together by their id_number but sort by the max amount for all years returned. I'm guessing I might have to write a case statement but I haven't figured it out yet. I Will update if I do. I wanted to ask for help also before I rack my mind for hours on this one.
Thank you very much in advance.
Based in your description, you want to sort the ids by the maximum sum in any year. If that is the case, use window functions in the
ORDER BY
:The second sort key is needed so all rows for a given
id_number()
are together when there are ties.