假设我有一个名为sell的表为父表,项目为子表
sell table
- id
- date
- total
items table
- id
- sell_id
- product_id
- qty
- price
我使用简单的架构将销售产品保存在我的商店中。我想每天创建可以显示sum of total from sells table
和sum of qty from items table
我的预期结果是这样的
date | sum total | sum qty
01 300 4
02 4300 32
我尝试使用像下面这样的sql语句
SELECT min(date) as `date`
, sum(sell.total) AS `sum total`
, sum(item.qty) AS `sum qty`
FROM `sell`
join `item`
ON sell.id = item.sell_id
WHERE month(date)='10'
GROUP
BY date(sell.date)
ORDER
BY date(sell.date)
在sql触发后,我得到的结果是日期和数量字段返回正确的值,但总计不正确。
如何解决我的查询以获取具有正确值的所有字段?
也许你想要:
select date, sum(total), sum(qty)
from ((select date, total, null as qty
from sales
) union all
(select s.date, null, i.qty
from items i
sales s
on i.sale_id = s.id
)
) si
group by date