Author |
Topic |
thiyait
Yak Posting Veteran
70 Posts |
Posted - 2014-06-03 : 01:52:20
|
Hi i have a query which is giving result like thisMoth POamount INvoiceamount PAckslipamount etc...1 12334 444325 3453242 43433 435 34523 34333 353 34344 1234 NULL NULLWant transpose into like thisheader 1 2 3 4 POamount 12334 43433 34333 1234INvoiceamount 444325 435 353 NULL PAckslipamount 345324 3452 3434 NULLetc..Please help how to write query using pivot\unpivot for this or any pointers. Thanks in advancethiya |
|
stepson
Aged Yak Warrior
545 Posts |
Posted - 2014-06-03 : 02:52:33
|
[code];with aCTEAS( select 1 as CustID,1 as [Month],12334 as POamount,444325 as INvoiceamount,345324 as PAckslipamount Union all select 1,2, 43433, 435, 3452 union all select 1,3, 34333, 353, 3434 union all select 1,4, 1234, NULL, NULL),PoCTEAS (select 'PoAmount' as header, [month],PoAmount FROM aCTE),InCTEAS (select 'INvoiceamount' as header, [month],INvoiceamount FROM aCTE),PACTEAS (select 'PAckslipamount' as header, [month],PAckslipamount FROM aCTE)select * from PoCTE Pivot( SUM(POamount) FOR [Month] IN ([1],[2],[3],[4]))AUNION ALLselect * from InCTE Pivot( SUM(INvoiceamount) FOR [Month] IN ([1],[2],[3],[4]))AUNION ALLselect * from PaCTE Pivot( SUM(PAckslipamount) FOR [Month] IN ([1],[2],[3],[4]))A[/code]output[code]header 1 2 3 4PoAmount 12334 43433 34333 1234INvoiceamount 444325 435 353 NULLPAckslipamount 345324 3452 3434 NULL[/code]sabinWeb MCP |
|
|
adsingh82
Starting Member
20 Posts |
Posted - 2014-06-04 : 01:10:14
|
you can find how to write pivot query using this below url[url]http://dotnetbites.com/example-pivot-unpivot-sql-server[/url]Regards,Alwyn.M |
|
|
MuralikrishnaVeera
Posting Yak Master
129 Posts |
Posted - 2014-06-06 : 05:33:33
|
What you need to use is UNPIVOT and then pivot the result set..Try thisCREATE TABLE DynamicPvt([Month] int,POamount int,INvoiceamount int,PAckslipamount int)INSERT INTO DynamicPvt VALUES(1 ,12334 ,444325 ,345324),(2 ,43433 ,435 ,3452),(3 ,34333 ,353 ,3434),(4 ,1234 ,NULL ,NULL)SELECT * FROM( SELECT Header,[MONTH],Value FROM ( SELECT CAST([MONTH] AS varchar(50)) AS [MONTH] ,CAST([POamount] AS varchar(50)) AS [POamount] ,CAST([INvoiceamount] AS varchar(50)) AS [INvoiceamount] ,CAST([PAckslipamount] AS varchar(50)) AS [PAckslipamount] FROM DynamicPvt ) s UNPIVOT (Value FOR Header IN ([POamount],[INvoiceamount],[PAckslipamount]))u)mPIVOT(MAX(Value) FOR [MONTH] IN ([1],[2],[3],[4]))p Notice that you won't get correct order as you expected ..---------------Murali KrishnaYou live only once ..If you do it right once is enough....... |
|
|
|
|
|