0
我想運行下面的查詢並通過0錯誤繼續得到除法。有時候除數中的平均值可能爲0.如果我使用平均值大於0的HAVING語句,則相同的查詢將起作用。但是,那些有效值將從結果中排除。由0錯誤和CASE劃分 - SQL
SELECT B.facility_desc Well,
B.facility_id "Facility ID",
(Cast(C.value AS NUMERIC(6, 0))),
(Avg(DISTINCT(Cast(A.value AS NUMERIC(6, 0))))),
((Avg(DISTINCT(Cast(A.value AS NUMERIC(6, 0))))) - (Cast(C.value AS NUMERIC(6, 0)))),
CASE
WHEN (Avg(DISTINCT(Cast(A.value AS NUMERIC(6, 0))))) = 0 THEN NULL
ELSE (((Avg(DISTINCT(Cast(A.value AS NUMERIC(6, 0))))) - (Cast(C.value AS NUMERIC(6, 0))))/(Avg(DISTINCT(Cast(A.value AS NUMERIC(6, 0))))))
END,
D.desc
FROM houston_vhs.historicalvalues A
LEFT JOIN houston_fac.fac_header B
ON LEFT(A.pointidlong, 10) = B.facility_id
LEFT JOIN houston_uis.realtimevalues C
ON LEFT(A.pointidlong, 10) = C.facilityid
LEFT JOIN houston_trs.table_header_record D
ON B.facility_table5 = D.table_entry
WHERE A.pointidlong LIKE 'DIMO_N8%_VGY'
AND A.pointtime > Now() - 7
AND A.unreliableflag = 'N'
AND B.facility_desc <> ''
AND B.facility_is_active = 'Y'
AND C.udc = 'RGAS'
AND C.value <> ''
GROUP BY B.facility_desc,
B.facility_id,
C.value,
D.desc
ORDER BY ((Avg(DISTINCT(Cast(A.value AS NUMERIC(6, 0))))) - (Cast(C.value AS NUMERIC(6, 0)))) ASC
我試圖改變CASE語句的順序,以及將值> 0,則公式如果沒有的話NULL無濟於事。我也試過使用NULLIF,這也是一個不行。任何見解都會被讚賞。
這是一個詳細的查詢,需要相當多的認知努力來解析和理解。如果您給出a)樣本數據集/輸出和/或b)表創建腳本,這將真正增加獲得答案的機會,以便人們可以自己運行此查詢並向您建議選項。 – prabugp