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.
WHERE (YEAR(period) >= 2010 AND YEAR(period) < 2021)don't use syntax like this; it's not SARGable. Use proper date logic:WHERE period >= '20100101' AND period < '20210101'