我试图了解如何使用桌子上的条件进行部分求和。
我在这张桌子上:
CREATE TABLE [dbo].[test](
[Id] [int] NOT NULL,
[part] [varchar](50) NULL,
[value] [int] NULL,
[TimeValue] [int] NULL,
CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[test] ([Id], [part], [value], [TimeValue]) VALUES (1, N'part1', 50, 15)
GO
INSERT [dbo].[test] ([Id], [part], [value], [TimeValue]) VALUES (2, N'part1', 8, 12)
GO
INSERT [dbo].[test] ([Id], [part], [value], [TimeValue]) VALUES (3, N'part1', 12, 9)
GO
INSERT [dbo].[test] ([Id], [part], [value], [TimeValue]) VALUES (4, N'part1', 10, 20)
GO
INSERT [dbo].[test] ([Id], [part], [value], [TimeValue]) VALUES (5, N'part2', 6, 4)
GO
INSERT [dbo].[test] ([Id], [part], [value], [TimeValue]) VALUES (6, N'part2', 9, 15)
GO
所以
Id part value TimeValue
1 part1 50 15
2 part1 8 12
3 part1 12 9
4 part1 10 20
5 part2 6 4
6 part2 9 15
我想写一个选择,在pSum AS INT
part AS VARCHAR(50)
TimeValue AS INT
<=
列与of current row TimeValue
列的分区之和
我写了这个:
SELECT *, SUM(value) OVER (PARTITION BY part) AS pSum FROM test
自然而然:
Id part value TimeValue pSum
1 part1 50 15 80
2 part1 8 12 80
3 part1 12 9 80
4 part1 10 20 80
5 part2 6 4 15
6 part2 9 15 15
但这会在每个分区上总和,我必须考虑TimeValue条件才能得到这个:
Id part value TimeValue pSum
1 part1 50 15 70 (sum in part1 where TimeValue <= 15 : 12 + 8 + 50)
2 part1 8 12 20 (sum in part1 where TimeValue <= 12 : 12 + 8)
3 part1 12 9 12 (sum in part1 where TimeValue <= 9 : just 12)
4 part1 10 20 80 (sum in part1 where TimeValue <= 20 : 12 + 8 + 50)
5 part2 6 4 6 (sum in part2 where TimeValue <= 4 : just 6)
6 part2 9 15 15 (sum in part2 where TimeValue <= 15 : 9 + 6)
我已经为SQL 2012找到了解决方案的可能解决方案here:
SUM(value) OVER (PARTITION BY part ORDER BY TimeValue rows between unbounded preceding and current row ) AS pSum
但我使用的是SQL 2008
请帮忙。 提前谢谢。
答案 0 :(得分:2)
在SQL Server 2008中,没有真正有效的方法来执行此操作。一种方法使用outer apply
:
select t.*, v.cumesum
from test t outer apply
(select sum(t2.value)
from test t2
where t2.part = t.part and t2.timevalue <= t.timevalue
) v(cumesum);