2016-01-22 55 views
0

我收到錯誤「每個GROUP BY表達式都必須包含至少一個不是外部引用的列」。在SQL Server中運行以下查詢時。與GROUP BY一起使用CASE的SQL Server錯誤

DECLARE @runDate smalldatetime = GETDATE() 
SELECT @runDate AS RunDate, 
    Division, 
    Product , 
    CASE WHEN Score >= 0 AND Score <= 6 THEN 'GOOD' 
     WHEN Score IN (7,8) THEN 'EXCELLENT' 
     WHEN Score IN (9,10) THEN 'OUTSTANDING' 
     ELSE 'INVALID' END AS Rank, 
    COUNT(*) AS TOTAL 
    FROM CurrentAnalysis 
    WHERE TimeStamp > @runDate - 1 
      AND TimeStamp <= @runDate 
      AND Source IN ('XXX', 'AAA') 
    GROUP BY @runDate, 
       Division, Product, 
       CASE WHEN Score >= 0 AND Score <= 6 THEN 'GOOD' 
        WHEN Score IN (7,8) THEN 'EXCELLENT' 
        WHEN Score IN (9,10) THEN 'OUTSTANDING' 
        ELSE 'INVALID' END 

我在GROUP BY中給出了相同的CASE,但仍然得到相同的錯誤。有誰能夠幫助我?

回答

3

的錯誤信息與在group by包含的變量,如果你刪除它,你應該沒事吧:

GROUP BY Division, Product, 
      CASE WHEN Score >= 0 AND Score <= 6 THEN 'GOOD' 
       WHEN Score IN (7,8) THEN 'EXCELLENT' 
       WHEN Score IN (9,10) THEN 'OUTSTANDING' 
       ELSE 'INVALID' 
      END 
+0

如果我刪除從GROUP BY的話,那麼也同樣的錯誤將是輸出。如何計算沒有GROUP By子句的聚合函數COUNT ??? –

+1

是的,你不應該像我的代碼片段所顯示的那樣去除'case',只是'@ runDate'。 '案件'不是問題 – HoneyBadger

+0

哦,謝謝。那是錯誤。 –