I have a SQL Select statement where I need to return certain values depending on a condition. I need to return multiple values each time, but my understanding of the Case statement is that you can only return a single value for each case.
I’m getting around this by using UNION statements at the moment, but it all looks a bit cumbersome – is there a better way to do this? Basically, I have a bunch of prompts, each with a response of either “Yes”, “No” or “In Future” (I actually have more responses, but I’ll just use 3 for the example to keep it short!) – I need to produce a column for each response type, with a 1 as the value for the appropriate response, and a 0 for all others. It’s probably clearer to understand if you look at the SQL…
My (simplified) query looks like this:
SELECT branch,
promptType,
response,
1 AS 'Yes',
0 AS 'No',
0 AS 'Not Discussed'
FROM prompts
WHERE response = 'Y'
UNION
SELECT branch,
promptType,
response,
0 AS 'Yes',
1 AS 'No',
0 AS 'Not Discussed'
FROM prompts
WHERE response = 'N'
UNION
SELECT branch,
promptType,
response,
0 AS 'Yes',
0 AS 'No',
1 AS 'Not Discussed'
FROM prompts
WHERE response = 'D'
Have you considered creating a decoding table for the responses, and joining to that?
For example, this would create a table for decoding the responses:
…and then you could join to it to get similar (the same?) results as you’re getting with your UNION:
Might be an approach worth considering; it’s a more relational solution than your union, and probably easier to maintain.