当有人购买物品时我有付款表我添加了1条带有金额和日期的记录
一些买家需要额外的服务项目(运输支持......) 所以我有服务价格和payment_id的服务表
我想要这样的结果
date - Sum(payments) - Sum(services)
01-01-2016 - 200 - 100
02-01-2016 - 200 - 100
03-01-2016 - 100 - 0
我试过这个查询
SELECT DATE(FROM_UNIXTIME(date)),SUM(amount),SUM(price)
FROM payments
LEFT JOIN services ON payments.id = service.payment_id
GROUP BY DATE(FROM_UNIXTIME(date))
但返回重复的值 提前谢谢
答案 0 :(得分:2)
您需要使用连接两个表的子查询,并对每笔付款的价格求和。然后,您可以按日期对结果进行分组。
SELECT date, SUM(payments), SUM(services)
FROM (
SELECT DATE(FROM_UNIXTIME(p.date)) AS date, p.amount AS payments, IFNULL(SUM(s.price), 0) AS services
FROM payments AS p
LEFT JOIN services AS s ON p.id = s.payment_id
GROUP BY p.id
) AS subquery
GROUP BY date