Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
varunpant
Starting Member
3 Posts |
Posted - 2008-11-05 : 15:57:50
|
Hi,I want to transpose the values of a table using a query.OrchestraUserName UserCode RoleArchie UC001 ComposerArchie UC001 SingerBetty UC002 ComposerBetty UC002 SingerVeronica UC003 SingerJughead UC004 InstrumentBetty UC002 Instrument I want to transpose the values likeUserName UserCode Composer Singer InstrumentArchie UC001 1 1 0Betty UC002 1 1 1Veronica UC003 0 1 0Jughead UC004 0 0 1 Any ideas?Thanks for your help,Cheers, |
|
|
rohitkumar
Constraint Violating Yak Guru
472 Posts |
Posted - 2008-11-05 : 16:14:38
|
| read about PIVOT and UNPIVOT herehttp://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/ |
 |
|
|
hanbingl
Aged Yak Warrior
652 Posts |
Posted - 2008-11-05 : 16:17:29
|
| [code]declare @sample table (username varchar(20),usercode varchar(10),role varchar(20))insert into @sampleselect 'Archie','UC001','Composer'union allselect 'Archie','UC001','Singer'union allselect 'Betty','UC002','Composer'union allselect 'Betty','UC002','Singer'union allselect 'Veronica','UC003','Singer'union allselect 'Jughead','UC004','Instrument'union allselect 'Betty','UC002','Instrument'select * from @sampleselect distincta.username, b.* from (select * from @samplepivot(count(username)for role in (Composer, Singer, Instrument)) as p) b inner join @sample a on a.usercode = b.usercodeorder by b.usercode[/code] |
 |
|
|
varunpant
Starting Member
3 Posts |
Posted - 2008-11-05 : 16:19:46
|
| Thanks hanbingl and rohit,Cheers, |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-11-05 : 23:33:06
|
orselect usercode,username,sum(case when role='composer' then 1 else 0 end) as composer,sum(case when role='singer' then 1 else 0 end) as singer,sum(case when role='Instrument' then 1 else 0 end) as Instrumentfrom @samplegroup by usercode,usernameorder by usercode |
 |
|
|
varunpant
Starting Member
3 Posts |
Posted - 2008-11-05 : 23:49:46
|
| Thanks.Yes, this is also another way,Cheers, |
 |
|
|
|
|
|
|
|