Avatar of isames
isames
 asked on

SQL Query

I want to make every that satisfy my condition to = 1400.

I wrote:

Select GLDV_Alt
Case
When gldv_alt_div_n = '1209', '1120' , '1401'
then '1400'
Else 0
End As 'Region South
from gldv


This works if my list is just one division, but not when it's a list of divisions.

Do I have to do a bunch of When operators?

Please help.
Microsoft SQL ServerMicrosoft SQL Server 2008

Avatar of undefined
Last Comment
Vitor Montalvão

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Jim Horn

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ste5an

Yup, that's a possibility. Or use the IN clause:

SELECT  GLDV_Alt ,
        CASE WHEN gldv_alt_div_n IN ( '1209', '1120', '1401' ) THEN '1400'
             ELSE 0
        END AS 'Region South'
FROM    gldv;

Open in new window

Scott Pletcher

The final choice would be to use a lookup table.  The only real advantage of this method is less chance for error if the list of numbers changes and/or becomes more complex, as the query itself doesn't change, just the values loaded into the table.  For a very large gldv table, you might even notice some performance improvement.

CREATE TABLE #GLDV_Div (
    gldv_alt_div_n varchar(4) NOT NULL,
    result varchar(4) NOT NULL
    )
INSERT INTO #GLDV_Div VALUES('1209' , '1400')
INSERT INTO #GLDV_Div VALUES('1120' ,  '1400')
INSERT INTO #GLDV_Div VALUES('1401'  , '1400')


Select GLDV_Alt, isnull(lookup.result, '0') As 'Region South'
from gldv
left outer join #GLDV_Div lookup on lookup.gldv_alt_div_n = gldv.gldv_alt_div_n
Vitor Montalvão

isames, do you still need help with this question?
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23