2012-09-27 64 views
1

與我最後一個問題類似。繼承人我的代碼:SUM字段不加總和

SELECT TR.ITEMNO, 
     SUM (TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'PO' THEN 1 ELSE 0 END) AS SUM_IN, 
     SUM (TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'MH' THEN 1 ELSE 0 END) AS SUM_OUT 
    FROM IQMS.TRANSLOG TR 
    WHERE TR.ITEMNO = '200672' 
    GROUP BY TR.ITEMNO 
    HAVING SUM (TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'PO' THEN 1 ELSE -1 END) < 0 
    ORDER BY TR.ITEMNO 

該代碼運行良好,但它不彙總任何SUM_OUT。但我知道有一個事實,那就是那裏有數字需要總結。有什麼明顯的我失蹤了?提前致謝!! :)

+1

拿在前面的問題看看我的答案。 [Here](http://stackoverflow.com/questions/12617153/sql-summing-certain-items-in-a-column-and-subtracting-it-from-another-figure-in/12618508#12618508) –

+1

硬在沒有看到一些樣本數據的情況下找到任何「錯誤」。你能提供你的數據的一個子集,允許複製案件嗎? –

+0

...此外,請解釋'HAVING'子句背後的想法 –

回答

3

的Try ...

SUM (TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'PO' THEN 1 ELSE 0 END) 
OVER(PARTITION BY TR.ITEMNO) AS SUM_IN, 

SUM (TR.TRANS_QUAN * CASE TR.TRANS_TYPE WHEN 'MH' THEN 1 ELSE 0 END) 
OVER(PARTITION BY TR.ITEMNO) AS SUM_OUT,