这是正确的答案:
SELECT
p.product_name,
coalesce((sum((i.time_paid is null and i.time_canceled is null and i.time_refunded is null) * it.line_total_price)), 0) due,
coalesce((sum((i.time_paid is not null) * it.line_total_price)), 0) paid,
coalesce((sum((i.time_canceled is not null) * it.line_total_price)), 0) canceled,
coalesce((sum((i.time_refunded is not null) * it.line_total_price)), 0) refunded
FROM
PRODUCT p
LEFT JOIN invoice_item it ON p.id = it.product_id
LEFT JOIN invoice i ON it.invoice_id = i.id
GROUP BY
p.id, p.product_description
我只需要在当前代码中添加null和*total\ u price。
谢谢!
2条答案
按热度按时间cetgtptt1#
我认为你需要条件聚合。逻辑不是很明确(特别是对于
due
列),但我认为这应该接近您想要的:jc3wubiy2#
这会让你知道怎么做。您可能需要摆弄case语句内部的逻辑,以便它是正确的,但这只是一个开始: