简体   繁体   中英

Using CASE statement to combine data

I have the following code. The purpose is to take the data in the field AML_TYP_CD which is the level of education they finished. 20 and 25 are the same as is 30/35/ 40/45 and I need to write a case statement that counts them up together so a 25 would return as 20 etc, and then there are about 50 other codes for the level of education that i need to elimnate. What is the best way to do this because the CASE statements i am writing does not work. The CASE statement will go in the SELECT clause, The one I wrote that doesnt work was

CASE WHEN (AML_TYP_CD) = '20' OR '25' THEN Bachelors ELSE NULL END) As Bach_Degree

The rest of the code is:

    SELECT     dbo.TACCPLI.SYS_EMP_ID_NR, MAX(dbo.TACCPLI.AML_TYP_CD) AS DEG
FROM         dbo.TACCPLI INNER JOIN
                          (SELECT     dbo.v_TMS_employee_HR.GEMSID, dbo.v_TMS_employee_HR.TMS_ID
                            FROM          dbo.v_TMS_employee_HR INNER JOIN
                                                   dbo.v_sc17_TMS_Data_Career_Meeting_Rating ON 
                                                   dbo.v_TMS_employee_HR.TMS_ID = dbo.v_sc17_TMS_Data_Career_Meeting_Rating.Employee_ID
                            WHERE      (LEFT(dbo.v_sc17_TMS_Data_Career_Meeting_Rating.Meeting_Readiness_Rating, 2) IN ('14', '15')) AND 
                                                   (dbo.v_TMS_employee_HR.Job_Group_Code >= '72') AND (dbo.v_TMS_employee_HR.Job_Group_Code <= '79') AND 
                                                   (dbo.v_sc17_TMS_Data_Career_Meeting_Rating.Plan_Year = 2012) AND (dbo.v_TMS_employee_HR.Region NOT IN ('12', '13', '16', '17'))
                            GROUP BY dbo.v_sc17_TMS_Data_Career_Meeting_Rating.Meeting_Readiness_Rating, dbo.v_TMS_employee_HR.GEMSID, dbo.v_TMS_employee_HR.TMS_ID) 
                      AS HPS ON dbo.TACCPLI.SYS_EMP_ID_NR = HPS.TMS_ID
GROUP BY dbo.TACCPLI.SYS_EMP_ID_NR

Your syntax is wrong. You're going to want something like:

SELECT 
    CASE WHEN AML_TYP_CD = '20' OR AML_TYP_CD = '25' THEN 'Bachelor''s' 
         WHEN AML_TYP_CD = '30' OR AML_TYP_CD = '35' THEN 'Whatever'
         --Other cases
         WHEN AML_TYP_CD = '90' OR AML_TYP_CD = '95' THEN 'Something'
         ELSE 'Other'
    END AS Degree

Or a little cleaner in my opinion:

SELECT 
    CASE WHEN CONVERT(INT, AML_TYP_CD) < 30 THEN 'Bachelor''s' 
         WHEN CONVERT(INT, AML_TYP_CD) < 40 THEN 'Whatever'
         --Other cases
         WHEN CONVERT(INT, AML_TYP_CD) < 100 THEN 'Something'
         ELSE 'Other'
    END AS Degree

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM