Sql-Server
在案例語句中執行求和
我試圖在 case 語句中得到一個總和,但我得到了錯誤
無法對包含聚合或子查詢的表達式執行聚合函式
這是我的查詢語法
Select case when sc.ars = 0 then 0 else SUM(sc.ars / NULLIF(SUM(ic.lit),0)) end FROM salesconfig sc Left Join income ic On sc.empID = ic.empID
我如何需要更改此查詢,以便它給我結果而不是錯誤?
測試
Select case when sc.ars = 0 then 0 else SUM(sc.ars / NULLIF(SUM(ic.lit) OVER (PARTITION BY NULL),0)) end FROM salesconfig sc Left Join income ic On sc.empID = ic.empID
首先,我們需要創建一個工作數據集來預先匯總一些值:
WITH Dataset as ( SELECT sc.empID as empID, MAX(sc.ars) as ars, -- Avoid extra GROUP BY SUM(ISNULL(ic.lit,0)) as SumLit -- EDITED - fixed incorrect code copy. FROM salesconfig sc LEFT JOIN income ic ON sc.empID = ic.empID GROUP BY sc.empID ),
這避免了嵌套 SUM 語句的問題,該問題(正如您的錯誤消息通知您的那樣)是不允許的。
接下來是輸出查詢。我包含了兩個版本,一個是 empID,一個只是摘要:
-- by empId SELECT empID, CASE WHEN ars = 0 OR SumLit = 0 THEN 0 ELSE ars/SumLit END as OutputValue FROM Dataset -- Overall total SELECT SUM( CASE WHEN ars = 0 OR SumLit = 0 THEN 0 ELSE ars/SumLit END ) as OutputValue FROM Dataset
添加的 CASE 語句邏輯是為了避免可能的除以零問題。