MSSQL:如何显示GROUP BY查询中的TOP 10项?

时间:2016-12-16 13:00:37

标签: sql count group-by subquery

我有一个查询显示结果:

Year-Month  SN_NAME Raised Incidents
2015-11 A   14494
2015-11 B   8432
2015-11 D   5496
2015-11 G   4778
2015-11 H   4554
2015-11 C   4203
2015-11 X   3477
.......+ thousands more rows for 2015-11
2015-12 A   3373
2015-12 B   3322
2015-12 H   2814
2015-12 D   2745
......+ thousands more rows for 2015-12
......+ thousands more rows for 2016-01 - 2016-10
2016-11 B   2645
2016-11 C   2571
2016-11 E   2475
2016-11 D   2466
....+ thousands more rows for 2016-11

我需要从上个月按Raised_Incident计数选择TOP 10 SN_NAME,然后显示过去12个月的COUNTS。

我用来显示上述结果的查询是这样的:

DECLARE @startOfCurrentMonth DATETIME
SET @startOfCurrentMonth = DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)

SELECT 
    CONVERT(char(7),IM.SN_SYS_CREATED_ON,121) as "Year-Month"
    ,CI.SN_NAME
    ,COUNT(IM.SN_NUMBER) as "Raised Incidents"
FROM [dbo].[tab_IM_Incident] IM 
    LEFT JOIN [dbo].[tab_SNOW_CMDB_CI] CI on IM.SN_CMDB_CI = CI.SN_SYS_ID
WHERE 
    IM.SN_SYS_CREATED_ON >= DATEADD(month, -13, @startOfCurrentMonth) AND    IM.SN_SYS_CREATED_ON < @startOfCurrentMonth
    AND (IM.SN_U_SUB_STATE <> 'Cancelled' OR IM.SN_U_SUB_STATE IS NULL)
GROUP BY 
    CONVERT(char(7),IM.SN_SYS_CREATED_ON,121)
    , CI.SN_NAME
ORDER BY 
    CONVERT(char(7),IM.SN_SYS_CREATED_ON,121) 
    , COUNT(IM.SN_NUMBER) DESC

问题是我不知道如何将每个月的值限制为TOP10,因为查询总共返回了大约200 000行,而它应该返回13x10 = 130行。

预期输出完全与问题相同,但过去13个月仅限于每月排名前10行。

请告知。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望在最近一个月内排名前10位,然后查看数据中所有月份的事件。

这是一种方法:

with t as (
      your query here
     )
select t.*
from (select top 10 t.*
      from t
      order by YearMonth desc, RaisedIncidents desc
     ) top10 left join
     t
     on t.sn_name = top10.sn_name
order by YearMonth desc, RaisedIncidents desc;

请注意,top 10未在最近一个月过滤。相反,它按最新月份排序,然后RaisedIncidents。这假设最近一个月至少发生了10起事件。