Q&A for anime and manga fans
DECLARE @t TABLE(ColumnA INT, ColumnB VARCHAR(50)); INSERT INTO @t VALUES (2, 'a'), (3 , 'b'), (4 , 'c'), (5 , 'd'), (1 , 'a'); ;WITH cte AS ( SELECT ColumnB, SUM(ColumnA) asum FROM @t gROUP BY ColumnB ), cteRanked AS ( SELECT asum, ColumnB, ROW_NUMBER() OVER(ORDER BY ColumnB) rownum FROM cte ) select * from cte /* select * from cteranked to this: ColumnA ColumnB 3 a 6(=3+3) b 10(=4+3+3) c 15(=5+4+3+3) d */