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
When using ANDs and ORs you should enclose in parentheses to avoid unwanted results. ie:
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
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.