I have some unbalanced spreadsheet with structure
ID Date Val Date Val Date Val
1 2000/01/01 2 2000/12/31 1
2 1999/01/28 6 2001/02/01 5 2001/12/31 6
....
I want to rearrange it to something like the following
ID Date Val
1 2000/01/01 2
1 2000/12/31 1
2 1999/01/28 6
2 2001/02/01 5
2 2001/12/31 6
....
Please advise me how I can do this in MS SQL Server? Thank you!
The sample data:
create table tmp
(
id smallint not null,
date1 Date,
val1 smallint,
date2 date,
val2 smallint,
date3 date,
val3 smallint
);
insert into tmp(id, date1, val1, date2, val2) values (1, '2001-01-01',5,'2001-12-31',6);
insert into tmp(id, date1, val1, date2, val2, date3, val3) values (2, '1999-02-01',3,'2000-12-31',2, '2001-05-01',3);
select * from tmp
1 2001-01-01 5 2001-12-31 6 NULL NULL
2 1999-02-01 3 2000-12-31 2 2001-05-01 3
However the following code will return
select c.* from tmp cross apply
(
select id, date1, val1 from tmp where date1 is not null
union all
select id, date2, val2 from tmp where date2 is not null
union all
select id, date3, val3 from tmp where date3 is not null
)
as c
1 2001-01-01 5
1 2001-01-01 5
2 1999-02-01 3
2 1999-02-01 3
1 2001-12-31 6
1 2001-12-31 6
2 2000-12-31 2
2 2000-12-31 2
2 2001-05-01 3
2 2001-05-01 3
From SQL Server 2005 onwards you can apply a function/subquery to each row in a source-data set.
Previous to Sql Server 2005, you can do this as three separate queries unioned together.