如何在T-SQL中添加每一行?

时间:2017-05-25 05:32:10

标签: sql-server tsql

我的数据可能是每个地址约50条记录:

Id  AddressId   Income  Expense Revenue
----------------------------------------
1   1           100     200     300
2   1           150      20     200
3   1           160      80     800
4   1            50      90     200
5   1           600     700     500

现在我需要以下格式的数据:

Ids       Count Income  Expense Revenue
---------------------------------------
1           1    100     200     300
1,2         2    250     220     500
1,2,3       3    410     300    1300
1,2,3,4     4    460     390    1500
1,2,3,4,5   5   1060    1090    2000

每一行都是一个接一个地添加。

例如:

  • Ids 1,2是Id 1和2的总和
  • Ids 1,2,3是Id 1和2以及3的总和,依此类推

我不需要Ids列,我唯一需要的是总和

3 个答案:

答案 0 :(得分:3)

您可以像这样使用STUFFROW_NUMBER() OVER()SUM() OVER()

DECLARE @SampleData AS TABLE
(
    Id int, 
    AddressId int,
    Income int,
    Expense int,
    Revenue int
)

INSERT INTO @SampleData
VALUES
( 1, 1, 100, 200, 300),
( 2, 1, 150, 20 , 200),
( 3, 1, 160, 80 , 800),
( 4, 1, 50 , 90 , 200),
( 5, 1, 600, 700, 500)

SELECT 
      STUFF(
             (
             SELECT ',' + CAST(sd1.Id AS varchar(10))
             FROM @SampleData sd1
             WHERE sd1.AddressId = sd.AddressId AND sd1.Id <= sd.Id
             FOR XML PATH('')
             ), 
          1,1,'') AS Ids,
      Row_number() OVER(PARTITION BY sd.AddressId ORDER BY sd.Id) AS Count,
      sum(sd.Income)  OVER(PARTITION BY sd.AddressId ORDER BY sd.Id) AS Income,
      sum(sd.Expense)  OVER(PARTITION BY sd.AddressId ORDER BY sd.Id) AS Expense,
      sum(sd.Revenue)  OVER(PARTITION BY sd.AddressId ORDER BY sd.Id) AS Revenue
FROM @SampleData sd
ORDER BY sd.AddressId, sd.Id

演示链接:http://rextester.com/HRIWH92029

注意:最后一笔收入应该是2000而不是1600

答案 1 :(得分:1)

如果您正在使用SQL Server 2012及更高版本, 请使用以下查询来总结前一行

Select ID, 
count(*) OVER (PARTITION by AddressID
ORDER BY ID
ROWS BETWEEN unbounded PRECEDING AND current row) as[Count],
sum(Income) OVER (PARTITION by AddressID
ORDER BY ID
ROWS BETWEEN unbounded PRECEDING AND current row) Income,
sum(Expense) OVER (PARTITION by AddressID
ORDER BY ID
ROWS BETWEEN unbounded PRECEDING AND current row)Expense,
sum(Revenue) OVER (PARTITION by AddressID
ORDER BY ID
ROWS BETWEEN unbounded PRECEDING AND current row) Revenue from TableName

答案 2 :(得分:0)

如果您正在使用SQL Server 2008及更低版本,请使用以下查询来总结前一行。

Select ID, (select count(*) from Tablename A where A.Id<=Tablename.ID)[Count], 
(select sum(Income) from Tablename A where A.Id<=Tablename.ID) Income, (select 
sum(Expense) from Tablename A where A.Id<=Tablename.ID) Expense, (select 
sum(Revenue) from Tablename A where A.Id<=Tablename.ID) Revenue from Tablename