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.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Display First Col Records as Title

Author  Topic 

vjs2445
Starting Member

16 Posts

Posted - 2011-08-25 : 09:44:30
I have a table with two fields F1 and F2.

I need some help in SQL Query which display F1 as first Row (Like Title) and F2 column as rows.

For Example:
F1 F2
F1R1 F2R1
F1R1 F2R2
F1R2 F2R3

Output:
F1R1 F1R2
F2R1 F2R3
F2R1

Is it possible to get this kind of output via SQL Query?

Thanks for your help.



TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2011-08-25 : 11:49:31
You can use PIVOT to transpose your rows to columns. Looks like you output is wrong, isn't it? Shouldn't your last row in the first column be "F2R2"?

Do you know all your desired columns at design time or will it change as the table changes? If the columns will change each time your un it then search here for "dynamic pivot" for a solution.

Be One with the Optimizer
TG
Go to Top of Page

vjs2445
Starting Member

16 Posts

Posted - 2011-08-25 : 12:23:19
Hi TG,

Thanks and you are right it should be F2R2.

Do you any resources about PIVOT? I am very not familiar with that.

Regards,
Go to Top of Page

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2011-08-25 : 12:54:55
Besides google I'm partial to Books Online:
Using PIVOT and UNPIVOT

Be One with the Optimizer
TG
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-08-25 : 13:09:24
[code]SELECT
MAX(CASE WHEN F1 ='F1R1' THEN F2 ELSE NULL END) AS F1R1 ,
MAX(CASE WHEN F1 ='F1R2' THEN F2 ELSE NULL END) AS F1R2
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY F1 ORDER BY F2) AS Seq,* FROM Table)t
GROUP BY Seq
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -