带行号的前 100 总和

Top 100 sum with row number

我有 select:

select col1,col2,col3.....sum(colx) from t1 group by col1,col2,col3...

如何:

1- 显示总和 (colx1) 最高的前 100 行 ASC

2- 添加行号

使用ROW_NUMBERTOP:

SELECT TOP(100)
    col1,
    col2,
    col3,
    SUM(colx),
    Rn = ROW_NUMBER() OVER(ORDER BY SUM(colx) DESC)
FROM t1
GROUP BY
    col1,
    col2,
    col3
ORDER BY Rn

使用 TOP()ROW_NUMBER() :

SELECT TOP 100 t.*,
       ROW_NUMBER() OVER(ORDER BY sum_col DESC) as row_number 
FROM(
    select col1,col2,col3.....
           sum(colx) as sum_col
    from t1 
    group by col1,col2,col3...) t
ORDER BY sum_col