我有一个包含此字段的表:
EmpID,
Code,
Amount,
TransDate,
CM,
CMDate
我想要访问数据网格的是SUM
具有相同Amount
和Code
SUM
的所有CM
与Code
相同的Amount
然后将SUM(Amount)
减去SUM(CM)
,但如果结果为NULL
(例如,没有CM
到SUM并减去SUM(Amount)
)然后只需选择SUM(Amount)
。我想出了这个陈述:
SELECT
TransDate,
Code,
SUM(Amount) - SUM(CM) AS 'Result'
FROM DeductionTbl
WHERE
(EmpID = @empID)
GROUP BY Code, TransDate
ORDER BY TransDate
如果SUM(CM)
要减去SUM(Amount)
,我会得到结果值,但如果没有相同的NULL
,我会得到结果SUM(CM)
{ {1}}。我不希望数据网格上有Code
值。如果有NULL
值,则返回NULL
。有没有办法做到这一点?谢谢!
答案 0 :(得分:3)
使用ISNULL
s:
SELECT
TransDate,
Code,
isnull(SUM(isnull(Amount,0)),0) - isnull(SUM(isnull(CM,0)),0) AS 'Result'
FROM DeductionTbl
WHERE
(EmpID = @empID)
GROUP BY Code, TransDate
ORDER BY TransDate
注意:强>
运行查询时,
SUM(ISNULL(CM,0))
可能会返回NULL
空结果集也避免ANSI WARNINGS
关于aggregating NULL
。并且
ISNULL(SUM(CM),0)
不被视为可以为空。
答案 1 :(得分:0)
试试这个,在这种情况下,IsNull会将NULLS转换为零。
SELECT
TransDate,
Code,
SUM(Amount) - SUM(ISNULL(CM, 0)) AS 'Result'
FROM DeductionTbl
WHERE
(EmpID = @empID)
GROUP BY Code, TransDate
ORDER BY TransDate
答案 2 :(得分:0)
使用null值的任何操作通常都会导致null。您需要将空值处理为0.我们使用ISNULL函数 试试这个......
SELECT
TransDate,
Code,
SUM(Amount) - ISNULL(SUM(CM), 0) AS 'Result'
FROM DeductionTbl
WHERE
(EmpID = @empID)
GROUP BY Code, TransDate
ORDER BY TransDate