SUM组的SQL Case语句

时间:2017-11-03 07:11:09

标签: sql sql-server

我知道一定有像我这样的问题。好像我找不到问题,对不起要问这个问题。

以下是我的表格(SalesTransaction)

ID   |SalesID   |Amount   |AmountReceived |OutStanding |Paid
2041  1000       600000    600000          0            1
2042  1000       1500000   2000000        -500000       1
2043  1000       900000    0               900000       0
2047  1002       300000    0               300000       0

使用下面的SQL查询:

SELECT ID, 
       SalesID, 
       Amount, 
       AmountReceived, 
       OutStanding, 
       Paid, 
       (CASE 
          WHEN Paid = 0 THEN (SELECT SUM(OutStanding) 
                              FROM SalesTransaction 
                              WHERE Paid = 1 ) 
        ELSE 0 END) AS BalanceLastSchedule 
FROM dbo.SalesTransaction 
GROUP BY ID, SalesID, Amount, AmountReceived, OutStanding, Paid

我得到如下结果:

ID   |SalesID   |Amount   |AmountReceived |OutStanding |Paid |BalanceLastSch
2041  1000       600000    600000          0            1     0.00
2042  1000       1500000   2000000        -500000       1     0.00
2043  1000       900000    0               900000       0     -500000
2047  1002       300000    0               300000       0     -500000

我想在下面得到什么:

ID   |SalesID   |Amount   |AmountReceived |OutStanding |Paid |BalanceLastSch
2041  1000       600000    600000          0            1     0.00
2042  1000       1500000   2000000        -500000       1     0.00
2043  1000       900000    0               900000       0     -500000
2047  1002       300000    0               300000       0     0.00

感谢我从中获得帮助。感谢。

1 个答案:

答案 0 :(得分:2)

您的答案错误,因为您尚未加入内部查询以查找SalesId的总和。试试下面的脚本

SELECT
  SeqNo, 
 SalesID, 
 Amount, 
 AmountReceived, 
 OutStanding, 
 Paid,
 ISNULL((CASE 
          WHEN Paid = 0 THEN (SELECT SUM(OutStanding) 
                              FROM SalesTransaction 
                              WHERE Paid = 1
                                AND SalesId = T.SalesId) 
        ELSE 0 END),0.00) AS BalanceLastSchedule 
  FROM SalesTransaction T;

我刚在游览内部查询中添加了以下内容,并删除了“按条款”

AND SalesId = T.SalesId