2016-12-06 58 views
2

兩個表SQL sum()函數,並加入

ORDER_TABLE:

ORDER_ID | TARGET_QTY | 
----------------------- 
1  | 50  
2  | 100 
3  | 200 

ALLOC_TABLE:

ORDER_ID | TARGET_QTY | 
----------------------- 
1  |   50 
2  |   20 
2  |   30 
3  |  200 

我想回到ORDER_TABLE.ORDER_ID的其中SUM(ALLOC_TABLE.TARGET_QTY)爲訂單ID是< ORDER_TABLE.TARGET_QTY。防爆。以下所需的輸出:

ORDER_ID | 
--------- 
2 

所有幫助表示讚賞!

回答

2
SELECT 
at.ORDER_ID 
FROM 
    ALLOC_TABLE at 
    JOIN ORDER_TABLE ot ON at.ORDER_ID = ot.ORDER_ID 
GROUP BY 
    at.ORDER_ID, ot.TARGET_QTY 
HAVING 
    SUM(at.TARGET_QTY) < ot.TARGET_QTY 
+0

謝謝DVT! –

0

嘗試這一PLS

SELECT at.ORDER_ID 
FROM ALLOC_TABLE at 
full outer JOIN ORDER_TABLE ot ON at.ORDER_ID = ot.ORDER_ID 
GROUP BY at.ORDER_ID 
HAVING SUM(at.TARGET_QTY) < ot.TARGET_QTY