SQL查询月(按系统)

时间:2019-04-03 12:14:47

标签: sql-server

我正在为系统中断建立报告。该报告必须在一年中的每个月按系统总计系统中断,即使没有中断,我仍然希望为0。

这是一个可以正常工作的查询:

with Months as (
    select dateadd(month,datediff(month,0,getdate()) - n, 0) MonthDate
    from (values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11))dt(n))
SELECT  
    m.MonthDate,
    C.Name,
    Count(*) as 'Count'
from 
    Months m 
    LEFT OUTER JOIN Incident I
        on (m.MonthDate = DATEADD(MONTH, DATEDIFF(MONTH,0,i.CreatedDateTime),0))
    Inner JOIN CI C on C.RecId = I.SystemName_Valid
WHERE   
    I.CreatedDateTime >= DATEADD(MONTH,-11,GETDATE()) 
GROUP BY    
    m.MonthDate, C.Name

结果仅显示系统中断的日期。

我希望输出如下所示

MonthDate   Name     Count
1/1/2019    System1    0
1/1/2019    System2    0
1/1/2019    System3    0
1/1/2019    System4    0
2/1/2019    System1    0
2/1/2019    System2    0
2/1/2019    System3    0
2/1/2019    System4    1
3/1/2019    System1    1
3/1/2019    System2    0
3/1/2019    System3    0
3/1/2019    System4    0
4/1/2019    System1    0
4/1/2019    System2    0
4/1/2019    System3    0
4/1/2019    System4    0

尽管返回的数据集是

MonthDate   Name     Count
2/1/2019    System4    1
3/1/2019    System1    1

2 个答案:

答案 0 :(得分:2)

尝试将您的FROM子句更改为:

from 
    Months m 
    CROSS JOIN dbo.CI -- you want to have a row per month per system
    LEFT OUTER JOIN dbo.Incident I -- this needs to be *outer* so that combos
                                   -- without a match are still included
      ON (m.MonthDate = DATEADD(MONTH, DATEDIFF(MONTH,0,i.CreatedDateTime),0))
      AND C.RecId = I.SystemName_Valid
      AND I.CreatedDateTime >= DATEADD(MONTH,-11,GETDATE()) -- this is redundant

可选表放入INNER / ON子句或WHERE子句中时,您将进行外部联接(给我所有月份并包括 any 事件)当我们找到匹配的行时将它们排成一列)(内部事件(仅几个月内给我发生匹配事件的月份)。

我还要更改此内容

on (m.MonthDate = DATEADD(MONTH, DATEDIFF(MONTH,0,i.CreatedDateTime),0))

对此:

ON i.CreatedDateTime >= m.MonthDate
AND i.CreatedDateTime < DATEADD(MONTH, 1, m.MonthDate)

这将允许使用键中具有CreatedDateTime的现有(或将来)索引,根据事件表中的数据量,该索引可能有用,也可能不有用。您当前的表达式将强制扫描整个表,因为它必须评估每一行的输出。

答案 1 :(得分:0)

使用Aaron发布的内容,我修改了查询,并使其与以下内容一起使用:

with Months as (
    select dateadd(month,datediff(month,0,getdate()) - n, 0) MonthDate
    from (values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11))dt(n))
SELECT  
    m.MonthDate,
    CI.Name,
    (Select 
        count(*) 
    from 
        Incident I 
    where 
        i.SystemOutageIssue = 1 and I.CreatedDateTime >= m.MonthDate and 
        I.CreatedDateTime < DateAdd(day,1,EOMONTH(m.MonthDate)) and
        I.SystemName = CI.Name) as 'Count'
from 
    Months m 
    Cross JOIN CI
GROUP BY    
    m.MonthDate, CI.Name

感谢亚伦(Aaron)的帮助,我以前从未使用过Cross Join,反正不是这样。