需要在CASE表达式中添加子查询,该表达式是聚合函数的一部分

时间:2016-10-14 20:15:39

标签: sql-server subquery aggregate-functions

我需要添加状态设置为“重新打开”的记录数。但“重新开放”状态有几个ID。 这是“重新打开”状态的子查询:

SELECT (CASE WHEN s.sr_status_recid = 1 THEN 1 ELSE 0 END) AS Reopened
    from v_rpt_service s 
    where vsrv.sr_status_recid  in 
        (select distinct SR_Status_RecID from SR_Status where [Description] like '%Re-opened%'))

这是上述查询需要成为其中一部分的主要查询:

SELECT DATEPART(WK, vsrv.date_entered) as WkNumber,
       COUNT(vsrv.TicketNbr) AS OpenedIssues, --total ticket count
       SUM(CASE WHEN vsrv.Closed_Flag = 1 THEN 1 ELSE 0 END) AS ClosedIssues, --sum of tickets with closed_flag = 1
       (SELECT SUM(CASE WHEN s.sr_status_recid = 1 THEN 1 ELSE 0 END) 
        from v_rpt_service s 
        where vsrv.sr_status_recid  in 
            (select distinct SR_Status_RecID from SR_Status where [Description] like '%Re-opened%')) AS ReopenedIssues, 
       SUM(CASE WHEN vsrvy.Surveys_Completed = 1 THEN 1 ELSE 0 END) AS SurveysCompletedWithConnectWise,  -- Surveys_Completed flag in view is 1
       SUM(CASE WHEN Source = 'Portal' THEN 1 ELSE 0 END) AS IssueLoggedPortal,
       SUM(CASE WHEN Source = 'Email Connector' THEN 1 ELSE 0 END) AS IssueLoggedEmai
FROM v_rpt_service vsrv LEFT OUTER JOIN v_rpt_SurveysByTicket vsrvy ON vsrv.TicketNbr = Vsrvy.SR_Service_RecID  
WHERE vsrv.company_name <> 'XYZ Test Company' AND vsrv.date_entered BETWEEN '01/01/2016' AND '10/07/2016'
GROUP BY DATEPART(WK, vsrv.date_entered)
ORDER BY WkNumber   

如何使用CASE语句创建子查询并聚合CASE语句?

1 个答案:

答案 0 :(得分:0)

您可以使用CROSS APPLY

SELECT DATEPART(WK, vsrv.date_entered) as WkNumber,
       COUNT(vsrv.TicketNbr) AS OpenedIssues, --total ticket count
       SUM(CASE WHEN vsrv.Closed_Flag = 1 THEN 1 ELSE 0 END) AS ClosedIssues, --sum of tickets with closed_flag = 1
       SUM(CountReopen.YesNo) AS NumberOfReopen,
       SUM(CASE WHEN vsrvy.Surveys_Completed = 1 THEN 1 ELSE 0 END) AS SurveysCompletedWithConnectWise,  -- Surveys_Completed flag in view is 1
       SUM(CASE WHEN Source = 'Portal' THEN 1 ELSE 0 END) AS IssueLoggedPortal,
       SUM(CASE WHEN Source = 'Email Connector' THEN 1 ELSE 0 END) AS IssueLoggedEmail
FROM v_rpt_service vsrv 
  LEFT OUTER JOIN v_rpt_SurveysByTicket vsrvy 
    ON vsrv.TicketNbr = Vsrvy.SR_Service_RecID 
  CROSS APPLY (
     SELECT IIF(COUNT(*) > 0,1,0) YesNo
     FROM SR_Status 
     where [Description] like '%Re-opened%'
       AND SR_Status_ID = vsrv.sr_status_recid
  ) CountReopen(YesNo)
WHERE vsrv.company_name <> 'XYZ Test Company' 
  AND vsrv.date_entered BETWEEN '01/01/2016' AND '10/07/2016'
GROUP BY DATEPART(WK, vsrv.date_entered)
ORDER BY WkNumber