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 |
mchughl1
Starting Member
1 Post |
Posted - 2010-09-03 : 07:17:17
|
Hi,I have a dataset that I need to pivot two columns in.The column names are dynamic in that new values need to be catered for so I do not think I can use case statements. The dataset is shown as follows. Transo Segment Name P D1000000 SERVICE 1 0.1 721000000 SERVICE 2 0.1 721000000 NULL 0.2 801000000 SERVICE 6 0.2 1441000000 SERVICE 6 0.2 1441000000 SERVICE 1 0.1 751000000 SERVICE 2 0.1 75I want to pivot it like so! - some values hidden Transo S1P S2P S6P NULL S1D S2D S6D NULL1000000 0.2 0.2 0.4 0.2 147 147 288 80I am able to pivot one column, just not two using the code as follows.DECLARE @columns VARCHAR(max)DECLARE @cols NVARCHAR(MAX)SELECT @columns = STUFF(( SELECT DISTINCT TOP 100 PERCENT '],[' +niku.Z_RemoveChars(t2.SEGMENT_NAME) FROM Z_RPT_LABOUR_FILE_PIVOT AS t2 ORDER BY '],[' + niku.Z_RemoveChars(t2.SEGMENT_NAME) FOR XML PATH('') ), 1, 2, '') + ']' print @columnsDECLARE @query VARCHAR(max)SET @query = 'SELECT transno, '+ @columns + 'FROM Z_RPT_LABOUR_FILE_PIVOTPIVOT(max(DOLLAR)FOR [SEGMENT_NAME]IN (' + @columns + '))AS PERCgroup by transno, '+ @columns + ''EXECUTE(@query)Any help on how to achieve this will be gratefully appreciated |
|
Sachin.Nand
2937 Posts |
Posted - 2010-09-03 : 09:13:48
|
quote: Originally posted by mchughl1 Hi,I have a dataset that I need to pivot two columns in.The column names are dynamic in that new values need to be catered for so I do not think I can use case statements. The dataset is shown as follows. Transo Segment Name P D1000000 SERVICE 1 0.1 721000000 SERVICE 2 0.1 721000000 NULL 0.2 801000000 SERVICE 6 0.2 1441000000 SERVICE 6 0.2 1441000000 SERVICE 1 0.1 751000000 SERVICE 2 0.1 75I want to pivot it like so! - some values hidden Transo S1P S2P S6P NULL S1D S2D S6D NULL1000000 0.2 0.2 0.4 0.2 147 147 288 80I am able to pivot one column, just not two using the code as follows.DECLARE @columns VARCHAR(max)DECLARE @cols NVARCHAR(MAX)SELECT @columns =@columns+ STUFF(( SELECT DISTINCT TOP 100 PERCENT '],[' +niku.Z_RemoveChars(t2.SEGMENT_NAME) FROM Z_RPT_LABOUR_FILE_PIVOT AS t2 ORDER BY '],[' + niku.Z_RemoveChars(t2.SEGMENT_NAME) FOR XML PATH('') ), 1, 2, '') + ']' print @columnsDECLARE @query VARCHAR(max)SET @query = 'SELECT transno, '+ @columns + 'FROM Z_RPT_LABOUR_FILE_PIVOTPIVOT(max(DOLLAR)FOR [SEGMENT_NAME]IN (' + @columns + '))AS PERCgroup by transno, '+ @columns + ''EXECUTE(@query)Any help on how to achieve this will be gratefully appreciated
Maybe the red part marked above is what you are missing.Limitations live only in our minds. But if we use our imaginations, our possibilities become limitless. PBUH |
 |
|
|
|
|
|
|