将单个值添加到计数查询中

时间:2016-11-24 03:54:59

标签: sql-server aggregate-functions

我在下面的查询中返回了一些票数。我还希望查询返回计数中的单个票号。 这是查询:

;WITH CTE
AS
(
select SR_Service_RecID 
from SR_Audit 
where Audit_Text like 'Ticket status has been changed from % to "Internal"%' OR
      Audit_Text like 'Ticket status has been changed from % to "Closed"%' OR
      Audit_Text like 'Ticket status has been changed from % to "First Contact Resolution"%'
)
SELECT Board_Name, COUNT(DISTINCT A.SR_Service_RecID) AS 'Re-Opened Tickets'
FROM CTE 
JOIN SR_Audit A 
  ON CTE.SR_Service_RecID = A.SR_Service_RecID  
JOIN v_rpt_service vsrv 
  ON vsrv.TicketNbr = A.SR_Service_RecID
WHERE Audit_Text LIKE 'Ticket status has been changed from%"Re-Opened"%'
  AND vsrv.company_name <> 'XYZ Test Company' 
  AND vsrv.date_entered BETWEEN @StartDate AND @EndDate 
  AND Board_Name in (@BoardName)
GROUP BY Board_Name

它返回:

Board Name    Count
IT Services     4

我想让它归还:

 Board Name    Count    Ticket Number
 IT Services    4         12346
 IT Services    4         12445
 IT Services    4         56345
 IT Services    4         12384

如何将票号添加到结果中?

2 个答案:

答案 0 :(得分:1)

我不会尝试理解整个查询,但您需要使用窗口函数。

您案例的简化版本为:

 SELECT [BoardName],
        COUNT([Ticket Number]) Over (PARTITION BY [BoardName]) as [Count],
        [Ticket Number]
 FROM YourBoardTable

PARTITION BY [BoardName]可以解决问题,您不需要GROUP BY

选项B:您计算总数,然后加入回原始查询

WITH cte as ( 
     --Same as your current CTE
), filter as (
        SELECT Board_Name, 
               DISTINCT A.SR_Service_RecID AS 'Re-Opened Tickets'
        FROM CTE  ....
        -- Your filter query without COUNT / GROUP BY
), cnt as (
      SELECT [BoardName],
             COUNT([Re-Opened Tickets]) as COUNT
      FROM filter 
      GROUP BY [BoardName]
)
SELECT F.[BoardName],
       C.[Count],
       F.[Ticket Number]
FROM filter F
JOIN cnt C
  ON Y.[BoardName] = C.[BoardName]
带有过滤器的

选项C:您现在可以使用window function3

 SELECT [BoardName],
        COUNT([Re-Opened Tickets]) Over (PARTITION BY [BoardName]) as [Count],
        [Ticket Number]
 FROM filter

答案 1 :(得分:0)

试试这个

;WITH CTE
AS
(
select SR_Service_RecID 
from SR_Audit 
where Audit_Text like 'Ticket status has been changed from % to "Internal"%' OR
  Audit_Text like 'Ticket status has been changed from % to "Closed"%' OR
  Audit_Text like 'Ticket status has been changed from % to "First Contact Resolution"%'
)
SELECT cte.SR_Service_RecID,Board_Name, COUNT(DISTINCT A.SR_Service_RecID) AS 'Re-Opened Tickets'
FROM CTE 
JOIN SR_Audit A 
 ON CTE.SR_Service_RecID = A.SR_Service_RecID  
JOIN v_rpt_service vsrv 
 ON vsrv.TicketNbr = A.SR_Service_RecID
WHERE Audit_Text LIKE 'Ticket status has been changed from%"Re-Opened"%'
 AND vsrv.company_name <> 'XYZ Test Company' 
 AND vsrv.date_entered BETWEEN @StartDate AND @EndDate 
 AND Board_Name in (@BoardName)
GROUP BY cte.SR_Service_RecID,Board_Name