SUM一列然后SUBTRACT到另一列的SUM

时间:2015-01-27 03:30:03

标签: sql-server datagrid

我有一个包含此字段的表:

EmpID,
Code,
Amount,
TransDate,
CM,
CMDate

我想要访问数据网格的是SUM具有相同AmountCode SUM的所有CMCode相同的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。有没有办法做到这一点?谢谢!

3 个答案:

答案 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