-, .
create table t1 (
id int, act char(1), scd date
)
create table t2 (
id int, decs varchar(4), dcd date
)
insert into t1 values
( 1, 'y', '20000115'),
( 1, 'n', '20030120'),
( 2, 'n', '20020125'),
( 2, 'y', '20030115'),
( 2, 'n', '20100120'),
( 3,'y','20050125'),
( 3,'y','20070120'),
( 3,'n','20110115')
insert into t2 values
(1,'buy','20000515' ),
(1,'sell', '20100520' ),
(1,'sell', '20120525' ),
(2,'hold', '20040515'),
(2,'buy', '20110510' ),
(3,'sell', '20080515'),
(3,'buy','20110525' )
with decisions as (
select row_number() over (partition by id order by dcd) as rn,
id, decs, dcd from t2
),
activities as
(
select row_number() over (partition by id order by scd) as rn,
id, act, scd from t1
)
select dec_to.id, x.from_act, x.to_act, x.scd, x.from_act, x.to_act, x.scd as scd, dec_from.decs as from_dec, dec_to.decs as to_dec, dec_to.dcd from decisions dec_from
right outer join decisions dec_to on dec_from.id = dec_to.id and
dec_to.rn = dec_from.rn + 1
outer apply (
select top 1 act_to.id, act_from.act as from_act, act_to.act as to_act, act_to.scd
from activities act_to
left outer join activities as act_from
on act_from.id = act_to.id and act_from.rn = act_to.rn - 1
where act_to.id = dec_to.id and act_to.scd <= dec_to.dcd
order by act_to.scd desc
) x
order by dec_to.id, dec_to.rn
, . , . , , , , .
, , "" .
ID FROM_ACT TO_ACT SCD FROM_DEC TO_DEC DCD
1 y 2000-01-15 buy 2000-05-15
1 y n 2003-01-20 buy sell 2010-05-20
1 y n 2003-01-20 sell sell 2012-05-25
2 n y 2003-01-15 hold 2004-05-15
2 y n 2010-01-20 hold buy 2011-05-10
3 y y 2007-01-20 sell 2008-05-15
3 y n 2011-01-15 sell buy 2011-05-25
SQLFiddle