Let’s make this easy.
I have a table.
visitID studentname dob roll.no value displIndex propID
200019 rob 05/18/1937 101 smoking 2 83
200019 rob 05/18/1937 101 2 91
200019 rob 05/18/1937 101 alcohol 1 83
200019 rob 05/18/1937 101 1 91
200020 henry 08/20/1987 102 smoking 2 83
200020 henry 08/20/1987 102 2 91
200021 king 09/21/1982 103 alcohol 1 83
200021 king 09/21/1982 103 1 91
I have a table of a similar kind.
Now what I am trying to do is if there is no display index of 1 for that particular visitID of that student, then in the case statement return a value of '779'.
select visitID,studentname
,dob
,roll.no
,value
,dispIndex
,propID
,case
WHEN (PATINDEX('%smoking%',value) >0 OR
(PATINDEX('%sometimes smoking%',value) > 0) THEN
'777'
WHEN (PATINDEX(%not smoking%,value) >0 OR
(PATINDEX(%do not smoke%,value) >0_ THEN
'778'
WHEN (ISNULL(CAST(value as varchar(max)),'')='') THEN
'779'
ELSE
'779'
END VALUE
Here King doesn’t have a record under smoking. So I want it to go into the 779 bucket. How can I perform that?
Not sure why you’re doing a cast here (based on your sample data), so change this:
To this:
Also — realize that the way you’re doing your wildcards, all of your ‘not smoking’ values are going to be ‘777’ because they match the first pattern
(PATINDEX('%smoking%',value)(i.e., the 2nd pattern won’t even be checked).EDIT
answers to your questions in the comment:
1) How will it pull the record of king–>smoking–>displayIndex 2?
Answer: There is no record in your sample set for King with a displayindex of 2. You can’t pull a record that isn’t there.
2) I want to check for … alcohol records.
Answer: You already solved that problem for the smokers & non-smokers. Just do the same kind of thing for alchohol. For example:
WHEN PATINDEX('%alchohol%',value) > 0 THEN '779'3) I would like to put the king student under 779
Answer: He is. The way a
CASEstatement works, if none of theWHENconditions evaluate totrue(i.e.,...WHEN PATINDEX('%smoking%',value) > 0) then the ELSE statement is used. Since none of the WHEN statements will evaluate totruefor King, he will be under779.