insert into @temp values('01/01/2004',1,94.18)
insert into @temp values('01/01/2004',2,92.11)
insert into @temp values('01/01/2004',3,91.34)
insert into @temp values('01/01/2004',4,90.09)
insert into @temp values('01/01/2004',5,99.34)
insert into @temp values('01/02/2004',1,97.49)
insert into @temp values('01/02/2004',2,94.34)
insert into @temp values('01/02/2004',3,95.78)
insert into @temp values('01/02/2004',4,94.34)
insert into @temp values('01/02/2004',5,94.66)
insert into @temp values('01/03/2004',1,94.55)
insert into @temp values('01/03/2004',2,94.24)
insert into @temp values('01/03/2004',3,95.78)
insert into @temp values('01/03/2004',4,94.34)
insert into @temp values('01/03/2004',5,94.67)
select [date],
sum( case when yr_num = 1 then price else 0 end) as '1',
sum( case when yr_num = 2 then price else 0 end) as '2',
sum( case when yr_num = 3 then price else 0 end) as '3',
sum( case when yr_num = 4 then price else 0 end) as '4',
sum( case when yr_num = 5 then price else 0 end) as '5'
from @temp
group by [date]
granate
ASKER
Thanks for the reply;
Like the answer, but it won't work if there are 10000 records in the table (several years worth). Anyway to do what you recommended without coding out each date?
JimV_ATL
The intial "insert into @temp" statements are just sample data.
You don't have to code out anything new for each date. You do have to code a column for each possible value for yr_num. How many possible values are there for yr_num?
A true example of the table would include 22 records for each date and there is approx. 10 years worth of data in the table ( well over 15000 records). There will be 22 records, all with the same date value, but the yr num will be 1-22 and the Price will obviously vary.
declare @temp table ([date] datetime, yr_num int, price decimal(19,2))
insert into @temp values('01/01/2004',1,94.1
insert into @temp values('01/01/2004',2,92.1
insert into @temp values('01/01/2004',3,91.3
insert into @temp values('01/01/2004',4,90.0
insert into @temp values('01/01/2004',5,99.3
insert into @temp values('01/02/2004',1,97.4
insert into @temp values('01/02/2004',2,94.3
insert into @temp values('01/02/2004',3,95.7
insert into @temp values('01/02/2004',4,94.3
insert into @temp values('01/02/2004',5,94.6
insert into @temp values('01/03/2004',1,94.5
insert into @temp values('01/03/2004',2,94.2
insert into @temp values('01/03/2004',3,95.7
insert into @temp values('01/03/2004',4,94.3
insert into @temp values('01/03/2004',5,94.6
select [date],
sum( case when yr_num = 1 then price else 0 end) as '1',
sum( case when yr_num = 2 then price else 0 end) as '2',
sum( case when yr_num = 3 then price else 0 end) as '3',
sum( case when yr_num = 4 then price else 0 end) as '4',
sum( case when yr_num = 5 then price else 0 end) as '5'
from @temp
group by [date]