适用于 Sql Server 2008:http ://www.sqlfiddle.com/#!3/4b7cb/2
with a as
(
select z.id,z.account,z.date, z.value, coalesce(x.id,-1) as grp
from tbl z
outer apply
(
select top 1 y.id
from tbl y where y.id < z.id and y.value > 0
order by y.id desc
) as x
)
select
id = max(id),
account = max(account),
value = sum(value),
date = max(date)
from a
group by grp
order by id
数据样本:
CREATE TABLE [tbl]
([ID] int, [account] varchar(3), [Value] int, [date] date);
INSERT INTO [tbl]
([ID], [account], [Value], [date])
VALUES
(0, 'Tom', 10, '2001-06-07 00:00:00'),
(1, 'Tom', -9, '2001-06-08 00:00:00'),
(2, 'Tom', -5, '2001-06-09 00:00:00'),
(3, 'Tom', -4, '2001-06-10 00:00:00'),
(4, 'Tom', 20, '2001-06-11 00:00:00'),
(5, 'Tom', 30, '2001-06-12 00:00:00'),
(6, 'Tom', -4, '2001-06-13 00:00:00'),
(7, 'Tom', -5, '2001-06-14 00:00:00'),
(8, 'Tom', 7, '2001-06-15 00:00:00'),
(9, 'Tom', -5, '2001-06-16 00:00:00'),
(10, 'Tom', -5, '2001-06-16 00:00:00'),
(11, 'Tom', 10, '2001-06-16 00:00:00'),
(12, 'Tom', -2, '2001-06-17 00:00:00');
输出:
ID ACCOUNT VALUE DATE
0 Tom 10 2001-06-07
4 Tom 2 2001-06-11
5 Tom 30 2001-06-12
8 Tom -2 2001-06-15
11 Tom 0 2001-06-16
12 Tom -2 2001-06-17
这个怎么运作:
select *, coalesce(x.id,-1) as z_id
from tbl z
outer apply
(
select top 1 y.id
from tbl y where y.id < z.id and y.value > 0
order by y.id desc
) as x
order by z.id desc;
输出:
ID ACCOUNT VALUE DATE Z_ID
12 Tom -2 2001-06-17 11
11 Tom 10 2001-06-16 8
10 Tom -5 2001-06-16 8
9 Tom -5 2001-06-16 8
8 Tom 7 2001-06-15 5
7 Tom -5 2001-06-14 5
6 Tom -4 2001-06-13 5
5 Tom 30 2001-06-12 4
4 Tom 20 2001-06-11 0
3 Tom -4 2001-06-10 0
2 Tom -5 2001-06-09 0
1 Tom -9 2001-06-08 0
0 Tom 10 2001-06-07 -1