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"时遇到问题 我已按上述方式编写了查询,但结果不准确。事实上,每个类别的收入总和计算的数量几乎相同,但实际上它应该是不同的(尽管计数是正确的)。
如果你能指出我错过的或做错了,我们将不胜感激!
谢谢:)
答案 0 :(得分: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是非匹配的默认结果。