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 |
|
srivatsahg
Yak Posting Veteran
71 Posts |
Posted - 2009-07-01 : 07:48:37
|
Hello Programmers..I need a sql query similar to PIVOT transformation.I have a table containing 3 Columns ... STEP | Label | Value --------------------1 | Good | Enabled2 | Better| Enabled3 | Best | Disabled I need a sql query to get the results as STEP | Good | Better | Best--------------------------------------------1 | Enabled | NULL | NULL2 | NULL | Enabled | NULL3 | NULL | NULL | Disabled Looks the query needs to display the transpose of a matrix Any help in this direction appreciatedSrivatsa |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2009-07-01 : 07:54:36
|
According to Books Online,SELECT p.Step, p.Good, p.Better, p.BestFROM Table1 AS tPIVOT (MAX(Value) FOR Label IN ([Good], [Better], [Best])) AS p N 56°04'39.26"E 12°55'05.63" |
 |
|
|
srivatsahg
Yak Posting Veteran
71 Posts |
Posted - 2009-07-01 : 08:13:12
|
Hello PesoThanks a ton for your help.The query works like a butter.I was aware using PIVOT operator but wasnt aware using the MAX operator to return non-integer fields as resultsThanks againSrivatsaquote: Originally posted by Peso According to Books Online,SELECT p.Step, p.Good, p.Better, p.BestFROM Table1 AS tPIVOT (MAX(Value) FOR Label IN ([Good], [Better], [Best])) AS p N 56°04'39.26"E 12°55'05.63"
|
 |
|
|
Nageswar9
Aged Yak Warrior
600 Posts |
Posted - 2009-07-01 : 08:15:16
|
| Hi try this toodrop table #tempcreate table #temp ( STEP varchar(32),Label varchar(32),Value varchar(32) )insert into #temp select 1 ,'Good' ,'Enabled'insert into #temp select 2 ,'Better','Enabled'insert into #temp select 3 ,'Best' ,'Disabled'DECLARE @strcols VARCHAR(MAX), @values VARCHAR(MAX),@string VARCHAR(MAX)select @strcols = '' , @values = '' ,@string = '' SELECT @strcols = @strcols + ', ([' + Label + ']) ', @values = @values + ', ['+ Label + ']'from ( select distinct Label from #temp ) tselect @string = 'select STEP'+@strcols+' from #temp pivot(max(Value) for Label in (' + stuff(@values,1,1,'') + '))p'print(@string) exec(@string) |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-07-01 : 12:38:21
|
whats the need of dynamic sql here. the values to pivot are static so peso's suggestion or below will be enoughSELECT STEP,MAX(CASE WHEN Label='Good' THEN Value ELSE NULL END) AS Good,MAX(CASE WHEN Label='Better' THEN Value ELSE NULL END) AS Better,MAX(CASE WHEN Label='Best' THEN Value ELSE NULL END) AS BestFROM TableGROUP BY STEP |
 |
|
|
|
|
|
|
|