Reputation: 11
Can you please tell me if SQL code below makes sense. I am using multiple ANDs
and OR
in CASE WHEN
.
Thanks for your help!
SELECT id, period,
CASE WHEN state = 'group8' AND mathscore = 0 AND manager = '' OR manager ISNULL
THEN 'Tom' ELSE manager END AS mgr,
CASE WHEN state = 'group8' AND mathscore = 0 AND associate = '' OR associate
ISNULL THEN 'Dick' ELSE associate END AS asso,
CASE WHEN state = 'group8' AND mathscore = 0 AND analyst = '' OR analyst ISNULL
THEN 'Harry' ELSE analyst END AS a
FROM class.sections
Upvotes: 1
Views: 18668
Reputation: 8101
Without sample data to work with, I'd wager you're looking for something like this, with your blanks and NULLs grouped together with parentheses.
Also, I changed your ISNULL
s (a function, in some dialects) to IS NULL
(a state, in SQL Server, anyway).
SELECT
id
,period
,CASE
WHEN state = 'group8'
AND mathscore = 0
AND (manager = ''
OR manager IS NULL) THEN 'Tom'
ELSE manager
END AS mgr
,CASE
WHEN state = 'group8'
AND mathscore = 0
AND (associate = ''
OR associate IS NULL) THEN 'Dick'
ELSE associate
END AS asso
,CASE
WHEN state = 'group8'
AND mathscore = 0
AND (analyst = ''
OR analyst IS NULL) THEN 'Harry'
ELSE analyst
END AS a
FROM
class.sections;
Upvotes: 0
Reputation: 590
When using ANDs and ORs you should enclose in parentheses to avoid unwanted results. i.e:
CASE WHEN (state = 'group8' AND mathscore = 0)
AND (manager = '' OR manager ISNULL)
THEN 'Tom' ELSE manager END AS mgr
is not the same as:
CASE WHEN (state = 'group8' AND mathscore = 0 AND manager = '')
OR manager ISNULL
THEN 'Tom' ELSE manager END AS mgr
Upvotes: 4