2015-04-02 176 views
0

尋找一種優雅的方式來避免錯誤消息 無法對包含聚合或子查詢的表達式執行聚合函數。執行彙總的子查詢計劃

SELECT AccountName 
, SUM(CASE 
     WHEN CallFlag = 1 AND Attempts < c.nMaxAttempts 
      THEN 1 
      ELSE 0 
     END)CallRecords 
, SUM(CASE 
     WHEN CRC IN(
        SELECT szCRC COLLATE SQL_Latin1_General_CP1_CI_AS 
        FROM ContactCenter..CallDispositionMap 
        WHERE bBadRecord = 1) 
      THEN 1 
      ELSE 0 
     END)BadRecords 
FROM Calls; 

回答

0

您需要使用子選擇。而且您還需要使用Group BY在查詢上。試試這個,

SELECT 
    AccountName, 
    SUM(CallRecords) AS CallRecords, 
    SUM(BadRecords) AS BadRecords 
FROM 
    (
    SELECT AccountName 
, (CASE 
     WHEN CallFlag = 1 AND Attempts < c.nMaxAttempts 
      THEN 1 
      ELSE 0 
     END)CallRecords 
, (CASE 
     WHEN CRC IN(
        SELECT szCRC COLLATE SQL_Latin1_General_CP1_CI_AS 
        FROM ContactCenter..CallDispositionMap 
        WHERE bBadRecord = 1) 
      THEN 1 
      ELSE 0 
     END)BadRecords 
    FROM Calls) AS data 
    GROUP BY AccountName 
+0

真棒......謝謝! – cherrywood 2015-04-02 16:42:43