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 |
|
Jawad
Starting Member
17 Posts |
Posted - 2011-12-19 : 10:13:45
|
HiSQL Server 2008I want to create output columns at runtime for distinct values of column Cal_2create table T1(col_1 smallint,Col_2 varchar(10),Col_3 varchar(10));insert into T1 values (1,'a','abc');insert into T1 values (1,'a','pqr');insert into T1 values (1,'a','xyz');insert into T1 values (2,'b','lmn');insert into T1 values (2,'b','efg');insert into T1 values (1,'b','hij');insert into T1 values (1,'c','stu');select * from T1Col_1 Col_2 Col_31 a abc1 a pqr1 a xyz2 b lmn2 b efg1 b hij1 c stu By any procedure or query I wish to got following out putCol_1 a b c1 abc 1 pqr 1 xyz 1 hij 1 stu2 b lmn 2 b efg Or IdeallyCol_1 a b c1 abc,pqr,xyz hij stu2 lmn,efg WishesJ a w a d |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-12-19 : 11:01:26
|
| [code]create table #T1(col_1 smallint,Col_2 varchar(10),Col_3 varchar(10));insert into #T1 values (1,'a','abc');insert into #T1 values (1,'a','pqr');insert into #T1 values (1,'a','xyz');insert into #T1 values (2,'b','lmn');insert into #T1 values (2,'b','efg');insert into #T1 values (1,'b','hij');insert into #T1 values (1,'c','stu');;with cteas(select col_1,Col_2,stuff((select ',' + Col_3 from #T1 where col_1= t1.col_1 and Col_2 = t1.Col_2 for xml path('')),1,1,'') as col3listfrom (select distinct col_1,Col_2 from #T1) t1)select *from ctepivot(max(col3list) for col_2 in (a,b,c))pdrop table #T1output-----------------------------------------------col_1 a b c-----------------------------------------------1 abc,pqr,xyz hij stu2 NULL lmn,efg NULL[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
Jawad
Starting Member
17 Posts |
Posted - 2011-12-19 : 22:31:40
|
| Hi visakh16thanks, That is very close to what i need, buy i dont want to pass pivot values , i wish it always cater new values as well, dont want to hard code pivot like like a,b,c.Please help me out.WishesJ a w a d |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
|
|
|
|
|
|
|