Author |
Topic |
jollyguy77
Starting Member
4 Posts |
Posted - 2014-02-20 : 06:29:50
|
Hi, First of all, i am new to sql. Here is the sample (for both table1 and table2, i have created a "SNO" as primary key and it's also identity column)Table1------PID PNAME PartID--- ----- ------0 Length 11 Breadth 12 Height 10 Area 21 Volume 2Table2------SampleID PID Pvalue PartID-------- --- ------- ------0 0 10 10 1 10 10 2 10 11 0 20 11 1 20 11 2 20 10 0 10 20 1 10 2Depending upon the PartID, i must get the following resultsPARTID: 1SampleID Length Breadth Height-------- ------ ------- ------0 10 10 101 20 20 20PARTID: 2SampleID Area Volume-------- ---- ------0 10 10 How to achieve the desired output as mentioned above in SQL Server 2008?Thanks,Jollyguy |
|
stepson
Aged Yak Warrior
545 Posts |
Posted - 2014-02-20 : 07:12:28
|
[code];with Table1AS (select 0 PID,'Length' PNAME, 1 PartID union all select 1, 'Breadth', 1 union all select 2, 'Height', 1 union all select 0, 'Area' , 2 union all select 1, 'Volume', 2 ),Table2AS (select 0 SampleID,0 PID ,10 Pvalue, 1 PartID union all select 0, 1, 10, 1 union all select 0, 2, 10, 1 union all select 1, 0, 20, 1 union all select 1, 1, 20, 1 union all select 1, 2, 20, 1 union all select 0, 0, 10, 2 union all select 0, 1, 10, 2),aCTEAS ( SELECT TOP 100 PERCENT SampleID ,PNAME ,PValue ,T2.PartID FROM table1 T1 inner join table2 T2 on T1.PID=T2.PID AND T1.PartID=T2.PartID ORDER BY T2.PartID,SampleID )select PartID,SampleID,[Length],[Breadth],[Height],[Area],[Volume] from aCTE pivot (MIN(PValue) FOR [PNAME] IN ([Length],[Breadth],[Height],[Area],[Volume])) as pvt order by PartID [/code]output[code]PartID SampleID Length Breadth Height Area Volume1 0 10 10 10 NULL NULL1 1 20 20 20 NULL NULL2 0 NULL NULL NULL 10 10[/code]SsabinWeb MCP |
|
|
|
|
|