我当前的查询:
select stock.id, stock.name, sum(amount) from stock
left join stock_detail on stock.id = stock_detail.stock_id
where transact_at BETWEEN ('2018-06-15') and ('2018-06-16')
group by stock.id
但它不会显示在库存明细表上没有条目的其他库存。
表1:股票
id name
1 chicken
2 beef
3 pork
4 drink
表2:StockDetail
id stock_id type amount transact_date
1 1 in 1000 15/06/2018
2 1 in 500 15/06/2018
3 2 in 300 16/06/2018
我想要输出
id name total_amount
1 chicken 1500
2 beef 300
3 pork 0
4 drink 0
答案 0 :(得分:0)
您必须将日期谓词从WHERE
移至ON
:
select stock.id, stock.name, coalesce(sum(amount) , 0)
from stock
left join stock_detail
on stock.id = stock_detail.stock_id
and transact_date BETWEEN ('2018-06-15') and ('2018-06-16')
group by stock.id