2014-02-12 109 views
0

我有兩個表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的

+0

也許用SUM(coalesce(QRecived,0) - coalesce(IsuedQuan,0))替換主查詢中的SUM(QRecived-IsuedQuan)'會解決這個問題嗎? – FrankPl

回答

0
SELECT c.vaccine_id, 
     c.name, 
     SUM(IfNull(QRecived,0) - IfNull(IsuedQuan,0)) Quantity 
FROM vaccine c 
.... 

應該照顧那。

+0

是否支持sqllite ISNULL?閱讀[本](http://stackoverflow.com/questions/7999608/null-substitution-in-sqlite) – Arion

+0

排序。歡呼聲@Arion –

3

您不需要外部group by。問題是,當沒有比賽,該值是NULL,所以你需要與另一個值來代替它們:

SELECT v.vaccine_id, v.name, 
     coalesce(r.QReceived, 0) - coalesce(i.IssuedQuan, 0) as Quantity 
FROM vaccine v LEFT OUTER JOIN 
    (SELECT SUM(quantity_recieved) as QReceived, vaccine_id 
     FROM vaccine_detail 
     GROUP BY vaccine_id 
    ) r 
    ON r.vaccine_id = v.vaccine_id LEFT OUTER JOIN 
    (SELECT SUM(issued_quantity) as IssuedQuan, vaccine_id 
     FROM issued_item 
     GROUP BY vaccine_id 
    ) i 
    ON i.vaccine_id = v.vaccine_id; 

您可以使用isnull()coalesce(),但coalesce()是這樣做的ANSI標準功能。

+0

感謝您的解決方案。它完美的作品。再次感謝命名也。 – Dan

相關問題