【发布时间】:2016-12-24 09:37:42
【问题描述】:
3 张桌子。
table_customers - customer_id, name
table_orders - order_id, customer_id, order_datetime
table_wallet - customer_id, amount, type // type 1- credit, type 2- debit
需要获取所有客户、他们的总余额、他们的最后订单日期和订单 ID。如果客户没有将任何退货订单日期设置为 0000-00-00,订单 ID 设置为 0。
这是我的查询。
SELECT
C.customer_id,
C.name,
COALESCE( SUM(CASE WHEN type = 2 THEN -W.amount ELSE W.amount END), 0) AS value,
COALESCE( max( O.order_id ) , '0' ) AS last_order_id,
COALESCE( max( date( O.order_datetime ) ) , '0000-00-00' ) AS last_order_date
FROM
table_customers as C
LEFT JOIN
table_wallet as W
ON C.customer_id = W.customer_id
LEFT JOIN
table_orders AS O
ON W.customer_id = O.customer_id
group by C.customer_id
ORDER BY C.customer_id
一切都是正确的,除了客户的价值。从结果来看,它似乎被多次添加。
我在这里创建了小提琴。 http://sqlfiddle.com/#!9/560f2/1
查询有什么问题?谁能帮我解决这个问题?
编辑:预期结果
customer_id name value last_order_id last_order_date
1 abc 20 3 2016-06-22
2 def 112.55 0 0000-00-00
3 pqrs 0 4 2016-06-15
4 wxyz 0 0 0000-00-00
【问题讨论】:
-
对我来说看起来是正确的。想要添加预期结果以清楚说明吗?
-
@fancyPants,添加了有问题的预期结果。
标签: mysql join aggregate-functions