我目前正在研究一些sql的东西,但运行时遇到了一些问题。
我有这种查找现金交易的方法,并取消现金返还但有时没有现金交易,因此该值变为NULL而您无法从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
答案 0 :(得分:5)
也许COALESCE()
可以帮到你?
你可以试试这个:
SUM(COALESCE(tp.payment_amount, 0))
或
COALESCE(SUM(tp.payment_amount), 0)
COALESCE(arg1, arg2, ..., argN)
返回列表中的第一个非null参数。
答案 1 :(得分:1)
尝试将ISNULL放在SUM和ABS中,即在实际字段周围,如此
SUM(ISNULL(tp.payment_amount, 0))
SUM(ABS(ISNULL(tp.payment_amount, 0)))
答案 2 :(得分:1)
我没有在这里测试MS SQL,但将ISNULL
置于SELECT
附近会有效吗?也许,如果没有匹配的行,ISNULL
根本不会被触发......