2016-05-31 67 views
0
SELECT 
DATE_TRUNC('day', payment.paid_at) AS "DAILY", 
COUNT(CASE WHEN product.type = 'A' THEN 1 ELSE NULL END) AS "A count", 
SUM(CASE WHEN product.type = 'A' AND payment.price_currency_code='USD' THEN payment.price_amount*1080 ELSE payment.price_amount END) AS "A revenue", 
COUNT(CASE WHEN product.type = 'B' THEN 1 ELSE NULL END) AS "B count", 
SUM(CASE WHEN product.type = 'B' AND payment.price_currency_code='USD' THEN payment.price_amount*1080 ELSE payment.price_amount END) AS "B revenue" 

嗨,情況下,當結果不準確

當使用「CASE WHEN」 我已經寫了如上的查詢,但結果是不準確我有一個問題。實際上,每個類別的收入總和幾乎相同,實際上它應該是不同的(但計數是正確的)。

如果你能指出我失蹤或做錯了,我將不勝感激!

謝謝:)

回答

1

有沒有在你的ELSE語句中的錯誤,因爲它包括一切的時候,其實你可能是爲了不同的條件:

SELECT 
DATE_TRUNC('day', payment.paid_at) AS "DAILY", 
COUNT(CASE WHEN product.type = 'A' THEN 1 END) AS "A count", 
SUM(CASE WHEN product.type = 'A' AND payment.price_currency_code='USD' THEN payment.price_amount*1080 WHEN product.type = 'A' THEN payment.price_amount END) AS "A revenue", 
COUNT(CASE WHEN product.type = 'B' THEN 1 END) AS "B count", 
SUM(CASE WHEN product.type = 'B' AND payment.price_currency_code='USD' THEN payment.price_amount*1080 WHEN product.type = 'B' THEN payment.price_amount END) AS "B revenue" 

此外,case語句ELSE NULL不是必需的,因爲NULL是非匹配的默認結果。

+0

哦對!謝謝你的幫助,這很好地解決了問題:)謝謝! – tmhs