SQL SERVER查询分组后各组TOP N

--1.将数据根据需求分组并存入临时表
SELECT [分组标准1], [分组标准2], 聚合函数([排序标准]) AS [排序标准]
INTO #TABLE
FROM [TABLENAME]
GROUP BY [分组标准1],[分组标准2]

--2.为临时表分组排序,取前N位
SELECT *
FROM (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY [分组标准1],[分组标准2] ORDER BY [排序标准] DESC) AS INDX
	FROM #TABLE
) A
WHERE A.INDX <= N ---TOP N 则 <= N,TOP 3 则 <= 3

 

你可能感兴趣的:(SQL SERVER查询分组后各组TOP N)