June 19, 2012 at 3:24 pm
There is a crosstab table like below:
NAME--RED--BLUE--GREEN--YELLOW
AAA-----1
BBB-------------1
CCC-----------------------1
DDD-------------------------------------1
How to code to replace '1' with column's name?
NAME--RED--BLUE--GREEN--YELLOW
AAA-----RED
BBB-------------BLUE
CCC-----------------------GREEN
DDD------------------------------------YELLOW
June 19, 2012 at 3:31 pm
CASE Statement 🙂
June 19, 2012 at 3:37 pm
This?
DECLARE @ReadingTable TABLE
(
Name VARCHAR(100)
,RED VARCHAR(100)
,BLUE VARCHAR(100)
,GREEN VARCHAR(100)
,YELLOW VARCHAR(100)
)
;
INSERT INTO @ReadingTable (Name , RED, BLUE, GREEN,YELLOW)
SELECT 'AAA',1,0,0,0
UNION ALL SELECT 'BBB',0,1,0,0
UNION ALL SELECT 'CCC',0,0,1,0
UNION ALL SELECT 'DDD',0,0,0,1
SELECT Name
,RED = CASE WHEN RT.RED = 1 THEN 'RED'
ELSE ''
END
,BLUE = CASE WHEN RT.BLUE = 1 THEN 'BLUE'
ELSE ''
END
,GREEN = CASE WHEN RT.GREEN = 1 THEN 'GREEN'
ELSE ''
END
,YELLOW = CASE WHEN RT.YELLOW = 1 THEN 'YELLOW'
ELSE ''
END
FROM @ReadingTable RT
June 20, 2012 at 7:48 am
Thank you.
I learned your way before.
The problem is that there are about 200 rows and 30 columns in real table.
Is there another way to code it?
June 21, 2012 at 12:16 am
Here's another way but it's no prettier and no easier to maintain.
SELECT Name
,(SELECT CASE WHEN RED = 1 THEN 'RED' ELSE '' END
FROM (VALUES (RED)) x) AS RED
,(SELECT CASE WHEN BLUE = 1 THEN 'BLUE' ELSE '' END
FROM (VALUES (BLUE)) x) AS BLUE
,(SELECT CASE WHEN GREEN = 1 THEN 'GREEN' ELSE '' END
FROM (VALUES (GREEN)) x) AS GREEN
,(SELECT CASE WHEN YELLOW = 1 THEN 'YELLOW' ELSE '' END
FROM (VALUES (YELLOW)) x) AS YELLOW
FROM @ReadingTable
If you're stuck with 30 columns you need to transform in this fashion, there's probably no better way than ColdCoffee's suggestion (the traditional approach).
My thought question: Have you ever been told that your query runs too fast?
My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.
Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
Since random numbers are too important to be left to chance, let's generate some![/url]
Learn to understand recursive CTEs by example.[/url]
[url url=http://www.sqlservercentral.com/articles/St
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply