2017-04-18 22 views
2

假設我有以下表如何將條件總和聚合列添加到SQL查詢取決於前面的行?

|Id|Debtor|Creditor| 
| 0|0  |400  | 
| 1|1000 |0  | 
| 2|2000 |0  | 
| 3|0  |5000 | 

我需要在每一行添加兩列TotalDebtTotalCredit與單個行唯一的總計一個充滿另一種是零的條件。 這是我要查找的查詢結果。

|Id|Debtor|Creditor|TotalDebt|TotalCredit| 
| 0|0  |400  |0  |400  | 
| 1|1000 |0  |600  |0   | 
| 2|2000 |0  |2600  |0   | 
| 3|0  |5000 |0  |2400  | 

回答

3

下面是做到這一點的一種方法:

創建並填充樣本數據(保存我們這一步在你未來的問題)

DECLARE @T AS TABLE 
(
    id int, 
    Debtor int, 
    Creditor int 
) 

INSERT INTO @T VALUES 
(0, 0 , 400), 
(1, 1000, 0 ), 
(2, 2000, 0 ), 
(3, 0 , 5000) 

使用CTE同時爲債務人和債權人列的滾動總和:

;WITH CTE AS 
(
    SELECT id, 
      Debtor, 
      Creditor, 
      SUM(Creditor - Debtor) OVER(ORDER BY ID) As RollingSum 
    FROM @T 
) 

從CTE選擇:

SELECT Id, 
     Debtor, 
     Creditor, 
     IIF(RollingSum < 0, -RollingSum, 0) As TotalDebt, 
     IIF(RollingSum > 0, RollingSum, 0) As TotalCredit 
FROM CTE 

結果:

Id Debtor Creditor TotalDebt TotalCredit 
0 0  400   0   400 
1 1000 0   600   0 
2 2000 0   2600  0 
3 0  5000  0   2400 

See a live demo on rextester.

2

試試這個:

SELECT Id, Debtor, Creditor, 
     IIF(Debtor=0, 0, SUM(Debtor-Creditor) OVER (ORDER BY Id)) AS TotalDebt, 
     IIF(Creditor=0, 0, SUM(Creditor-DEbtor) OVER (ORDER BY Id)) AS TotalCredit 
FROM mytable 

Demo here

+0

如果你添加這行:'4,100,0',該怎麼辦?你的結果會在'TotalDebt'列中顯示'-2300',在'TotalCredit'列中顯示'0' ... http://rextester.com/RDCQT51162 –

+0

@ZoharPeled我認爲這是OP實際需要的。 –

+0

那麼,-2300的總債務實際上是2300的總抵免額,這正是我的建議所顯示的。我想我們將不得不等待OP做出迴應。 –

0

嘗試:

SELECT *, 
     case when [Debtor]> 0 then sum([Debtor] - [Creditor]) over (order by id) 
      else 0 end as TotalDebt, 
     case when [Creditor]> 0 then sum([Creditor] - [Debtor]) over (order by id) 
      else 0 end as TotalCredit 
FROM table1 

演示:http://rextester.com/HQCZQH39439

0

使用子查詢的計算爲小於或等於給定的「ID」

0

下面的查詢會爲你工作的所有條目的總和,如果你不希望使用IIF(這是特定版本),試試下面的查詢這會給你所需的確切輸出:

DECLARE @TableData AS TABLE(id int,Debtor int,Creditor int) 

INSERT INTO @TableData VALUES 
(0, 0, 400), 
(1, 1000, 0), 
(2, 2000, 0), 
(3, 0, 5000), 
(4, 10, 0), 
(5, 0, 20) 

;WITH SAMPLEDATA 
AS 
(
    SELECT *,0 TD,Creditor TC FROM @TableData WHERE ID=0 
    UNION ALL 
    SELECT T2.*, 
    CASE WHEN T2.Debtor=0 THEN 0 ELSE T1.TD+(T2.Debtor-T1.Creditor) END, 
    CASE WHEN T2.Creditor=0 THEN 0 ELSE T2.Creditor-T1.TD END 
    FROM SAMPLEDATA T1 JOIN @TableData T2 ON T1.id=T2.id-1 
) 
select * from SAMPLEDATA 

查詢的輸出,有一些額外的假數據:

--------------------------------- 
id Debtor Creditor TD TC 
--------------------------------- 
0 0  400  0  400 
1 1000 0  600  0 
2 2000 0  2600 0 
3 0  5000 0  2400 
4 10  0  -4990 0 
5 0  20  0  5010 
--------------------------------- 
相關問題