June 9, 2006 at 8:28 am
Hi to all,
I have this data:
S1 S2 Crit
1 3 9.0
2 3 8.0
3 3 7.0
1 5 1.0
2 5 2.0
3 5 3.0
and I need to make it:
S2 Crit1 Crit2 Crit3
3 9.0 8.0 7.0
5 1.0 2.0 3.0
Thank you for any help you can provide me.
June 9, 2006 at 1:24 pm
If the number of values for s1 is fixed (in your example - 3) - then you can use the following
create table #temp (s1 tinyint, s2 tinyint, crit float)
insert into #temp select 1, 3, 9.0
insert into #temp select 2, 3, 8.0
insert into #temp select 3, 3, 7.0
insert into #temp select 1, 5, 1.0
insert into #temp select 2, 5, 2.0
insert into #temp select 3, 5, 3.0
select s2,
(select crit from #temp t2 where t2.s2 = t1.s2 and t2.s1 = 1) as Crit1,
(select crit from #temp t2 where t2.s2 = t1.s2 and t2.s1 = 2) as Crit2,
(select crit from #temp t2 where t2.s2 = t1.s2 and t2.s1 = 3) as Crit3
from #temp t1
group by s2
Cheers
June 14, 2006 at 5:55 pm
This posted script from iecdba should do the trick...
http://www.sqlservercentral.com/scripts/viewscript.asp?scriptid=422
-
June 16, 2006 at 5:12 am
CK Bhatia - If you feel the need for speed, you should use this query instead:
select s2,
sum(case when s1 = 1 then crit else 0 end) as Crit1,
sum(case when s1 = 2 then crit else 0 end) as Crit2,
sum(case when s1 = 3 then crit else 0 end) as Crit3
from #temp t1
group by s2
Alberto - If you only need a static pivot, use the query above. If you need a dynamic piovt, these are the references I usually give:
http://www.sqlteam.com/item.asp?ItemID=2955
http://weblogs.sqlteam.com/jeffs/archive/2005/05/02/4842.aspx
I've not compared these to the reference Jason posted, but all are generally the same idea.
Ryan Randall
Solutions are easy. Understanding the problem, now, that's the hard part.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply