patternMinor
Using Same CASE WHEN Conditions For Multiple Query Columns
Viewed 0 times
casesamecolumnsqueryusingforconditionsmultiplewhen
Problem
Is there a "better" way to rewrite a
See the example below.
In non-sql psuedo-code, the code might look like:
Note:
SELECT clause where multiple columns use the same CASE WHEN conditions so that the conditions are only checked once?See the example below.
SELECT
CASE testStatus
WHEN 'A' THEN 'Authorized'
WHEN 'C' THEN 'Completed'
WHEN 'P' THEN 'In Progress'
WHEN 'X' THEN 'Cancelled'
END AS Status,
CASE testStatus
WHEN 'A' THEN authTime
WHEN 'C' THEN cmplTime
WHEN 'P' THEN strtTime
WHEN 'X' THEN cancTime
END AS lastEventTime,
CASE testStatus
WHEN 'A' THEN authBy
WHEN 'C' THEN cmplBy
WHEN 'P' THEN strtBy
WHEN 'X' THEN cancBy
END AS lastEventUser
FROM testIn non-sql psuedo-code, the code might look like:
CASE testStatus
WHEN 'A'
StatusCol = 'Authorized'
lastEventTimeCol = authTime
lastEventUserCol = authUser
WHEN 'C'
StatusCol = 'Completed'
lastEventTimeCol = cmplTime
lastEventUserCol = cmplUser
...
ENDNote:
- I am aware of the obvious normalization issues implied by the query. I only wanted to demonstrate the issue.
Solution
If all these columns are from the same table, you can use something like this:
SELECT
'Authorized' AS StatusCol,
authTime AS lastEventTimeCol,
authUser AS lastEventUserCol
FROM test
WHERE testStatus = 'A'
UNION ALL
SELECT
'Completed',
cmplTime,
cmplUser
FROM test
WHERE testStatus = 'C'
UNION ALL
SELECT
'In Progress',
strtTime,
strtUser
FROM test
WHERE testStatus = 'P'
UNION ALL
SELECT
'Cancelled',
cancTime,
cancUser
FROM test
WHERE testStatus = 'X' ;Code Snippets
SELECT
'Authorized' AS StatusCol,
authTime AS lastEventTimeCol,
authUser AS lastEventUserCol
FROM test
WHERE testStatus = 'A'
UNION ALL
SELECT
'Completed',
cmplTime,
cmplUser
FROM test
WHERE testStatus = 'C'
UNION ALL
SELECT
'In Progress',
strtTime,
strtUser
FROM test
WHERE testStatus = 'P'
UNION ALL
SELECT
'Cancelled',
cancTime,
cancUser
FROM test
WHERE testStatus = 'X' ;Context
StackExchange Database Administrators Q#18239, answer score: 7
Revisions (0)
No revisions yet.