SQL: How can i build a string from column values of one row?
-
27-05-2021 - |
Question
I have rows like this...
| NAME | RED | BLUE | GREEN |
LeAnn 1 0 1
Jim 0 0 0
Timothy 1 1 1
I want to write a select statement that would return the following rows...
| Name | Note |
LeAnn RED, Green
Jim
Timothy RED, BLUE, GREEN
How can I do this? I tried using case statement but would only get one value in Note instead of multiple values. Thanks!
My Attempt:
SELECT Name,
CASE
WHEN Red = 1 THEN 'Red' + ', '
WHEN Blue = 1 THEN 'Blue' + ', '
WHEN Green = 1 THEN 'Green' + ', '
END as Note
FROM MyTable
Solution
Since the cases are not mutually exclusive, you need three separate cases:
SELECT ('' +
CASE WHEN Red = 1 THEN 'Red, ' ELSE '' END
+ CASE WHEN Blue = 1 THEN 'Blue, ' ELSE '' END
+ CASE WHEN Green = 1 THEN 'Green, ' ELSE '' END
)
AS Note
FROM MyTable
OTHER TIPS
SELECT Name, CASE WHEN RED = 1 THEN "RED " ELSE "" END + CASE WHEN BLUE = 1 THEN "BLUE " ELSE "" END + CASE WHEN GREEN = 1 THEN "GREEN" ELSE "" END
FROM tableName
There needs to be 3 separate cases, or it will only do one of them.
You would need to update the above to handle the commas properly as well, but im too lazy to put that in
SELECT Name,
CONCAT(
IF(Red = 1, 'Red', ''),
IF(Red = 1 AND Blue = 1, ', ', ''),
IF(Blue = 1, 'Blue', ''),
IF(Red = 1 AND Green = 1 AND `Blue` = 0, ', ', ''),
IF(Blue = 1 AND Green = 1, ', ', ''),
IF(Green = 1, 'Green', '')
) AS Note
From Table
I think this should work! Let me know if it doesn't ;)
What about this?
select name, left(Note, abs(len(Note) - 1)) from (
select name, '' +
CASE WHEN Red = 1 THEN 'Red, ' ELSE '' END +
CASE WHEN Blue = 1 THEN 'Blue, ' ELSE '' END +
CASE WHEN Green = 1 THEN 'Green, ' ELSE '' END
as Note
from t
) final
SELECT
''
+ ISNULL(NULLIF(Red, 0), 'Red, ')
+ ISNULL(NULLIF(Blue, 0), 'Blue, ')
+ ISNULL(NULLIF(Green, 0), 'Green, ')
AS Note
FROM
TheTable
This will create a trailing comma that you'd have to trim. For example like this:
SELECT
REPLACE(
''
+ ISNULL(NULLIF(Red, 0), 'Red, ')
+ ISNULL(NULLIF(Blue, 0), 'Blue, ')
+ ISNULL(NULLIF(Green, 0), 'Green, ')
+ '$',
', $',
''
) AS Note
FROM
TheTable
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow