2011-05-12 64 views
3

我目前正在研究一些sql的東西,但在某個問題上運行。SUM上的NULL值存在SQL問題

我有這種方法,尋找現金交易,並摘下現金返還,但有時沒有現金交易,使價值變成了空值,你不能從NULL減去。 我試過在它周圍放置一個ISNULL,但它仍然變爲空。

任何人都可以幫助我嗎?

;WITH tran_payment AS 
(
SELECT 1 AS payment_method, NULL AS payment_amount, null as tran_header_cid 
UNION ALL 
SELECT 998 AS payment_method, 2 AS payment_amount, NULL as tran_header_cid 
), 
paytype AS 
(
SELECT 1 AS mopid, 2 AS mopshort 
), 
tran_header AS 
(
SELECT 1 AS cid 
) 
      SELECT p.mopid      AS mopid, 
        p.mopshort     AS descript, 
        payment_value AS PaymentValue, 
        ISNULL(DeclaredValue, 0.00) AS DeclaredValue 
      from paytype p 
        LEFT OUTER JOIN (SELECT CASE 
         When (tp.payment_method = 1) 
         THEN 
        (ISNULL(SUM(tp.payment_amount), 0) 
        - (SELECT ISNULL(SUM(ABS(tp.payment_amount)), 0) 
          FROM tran_payment tp 
          INNER JOIN tran_header th on tp.tran_header_cid = th.cid 
     WHERE payment_method = 998 
     )) 
    ELSE SUM(tp.payment_amount) 
    END as payment_value, 
    tp.payment_method, 
    0 as DeclaredValue 
    FROM tran_header th 
    LEFT OUTER JOIN tran_payment tp 
    ON tp.tran_header_cid = th.cid 
    GROUP BY payment_method) pmts 
    ON p.mopid = pmts.payment_method 
+1

你正在使用哪些DBMS? – 2011-05-12 09:12:51

+0

你可能在你的ELSE子句中缺少一個ISNULL()嗎? – 2011-05-12 09:18:02

+0

@Daniel從ISNULL,我想這是MS SQL – bpgergo 2011-05-12 09:21:44

回答

5

也許COALESCE()可以幫助你嗎?

你可以試試這個:

SUM(COALESCE(tp.payment_amount, 0)) 

COALESCE(SUM(tp.payment_amount), 0) 

COALESCE(arg1, arg2, ..., argN)返回列表中的第一個非空參數。

1

試圖把裏面ISNULL SUM和ABS也就是圍繞實際的現場,像這樣

SUM(ISNULL(tp.payment_amount, 0)) 

SUM(ABS(ISNULL(tp.payment_amount, 0))) 
+1

的事務不應該有任何區別在計算SUM時忽略NULL值。 SUM(x)'返回NULL的唯一時間將是如果所有輸入都是NULL,那麼只是將集合包裝在'ISNULL'中將具有相同的效果。 – 2011-05-12 09:24:44

1

我沒有MS SQL在這裏做測試,但將努力把ISNULL圍繞着SELECT?也許,ISNULL根本沒有被觸發,如果沒有匹配的行...