-2
如果任何這些列沒有返回值,試着返回0,在我的特殊情況下,'Past Due'沒有總值,所以它被返回,所以我在這裏獲得第二個片段的回報。如果這些數值沒有數值,我該如何返回?當總和沒有值時返回0總和 - sql server
SELECT ClientDeliveryStatus,
SUM(CASE
WHEN ClientDeliveryStatus = 'Past Due' THEN 1
WHEN ClientDeliveryStatus = 'Due Tomorrow' THEN 1
WHEN ClientDeliveryStatus = 'Due Today' THEN 1
WHEN ClientDeliveryStatus = 'Due Beyond' THEN 1
ELSE 0 END) AS Total
FROM Table1
GROUP BY ClientDeliveryStatus
當前結果:
ClientDeliveryStatus Total
Due Beyond 1
Due Today 3
Due Tomorrow 51
所需的結果:
ClientDeliveryStatus Total
Due Beyond 1
Due Today 3
Due Tomorrow 51
Past Due 0
實施例的數據:
TABLE1:
ClientDeliveryStatus
Due Tomorrow
Due Tomorrow
Due Tomorrow
Due Beyond
Due Beyond
Due Tomorrow
Due Beyond
Due Beyond
Due Beyond
Due Today
Due Today
CREATE TABLE1 Table1 (ClientDeliveryStatus VARCHAR(MAX))
INSERT INTO Table1 Values ('Due Tomorrow'), ('Due Tomorrow'), ('Due Tomorrow'), ('Due Beyond'), ('Due Beyond'), ('Due Beyond'), ('Due Beyond'), ('Due Today'),('Due Today')
group by by,其存在於實際查詢中,所以沒有問題。工會會更簡單還是更慢?我總是這樣認爲性能是一個因素,但是對於我來說,這比平均查詢更重要。 – wondergoat77
沒有關於工會,愚蠢的問題 – wondergoat77
@ wondergoat77。 。 。如果你有一個參考表的值,我不會感到驚訝。這將是最好的方法。 'UNION ALL'比'UNION'快。 –