我有兩個表Received和Issued,它們與ID字段有關。我試圖使用下面的查詢來獲得結果,並且它只在兩個表都有值時才起作用。但是,當一個表爲空時,查詢返回NULL值。我需要幫助,請SQL查詢:從不同的表中總結兩個不同的列
SELECT
c.vaccine_id,
c.name,
SUM(QRecived-IsuedQuan) Quantity
FROM
vaccine c
LEFT OUTER JOIN (
SELECT SUM(quantity_recieved) QRecived,vaccine_id from vaccine_detail group by vaccine_id
) a ON a.vaccine_id=c.vaccine_id
LEFT OUTER JOIN (
select SUM(issued_quantity) IsuedQuan,vaccine_id from issued_item group by vaccine_id
) b ON b.vaccine_id=a.vaccine_id "
GROUP BY c.vaccine_name,c.vaccine_id ";
注:上面的查詢會SQLite中被運行,這僅僅是通知你,SQLLITE不支持RIGHT & FULL JOIN的
也許用SUM(coalesce(QRecived,0) - coalesce(IsuedQuan,0))替換主查詢中的SUM(QRecived-IsuedQuan)'會解決這個問題嗎? – FrankPl