使用CASE语句组合数据

时间:2013-01-11 16:45:25

标签: case

我有以下代码。目的是获取AML_TYP_CD字段中的数据,这是他们完成的教育水平。 20和25与30/35 / 40/45相同,我需要编写一个案例陈述,将它们统计在一起,这样25个将返回20等,然后大约有50个其他代码用于教育水平我需要消除。这样做的最佳方法是什么,因为我写的CASE语句不起作用。 CASE语句将进入SELECT子句,我写的那个不起作用的是

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

其余代码是:

    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

1 个答案:

答案 0 :(得分:1)

你的语法错了。你会想要这样的东西:

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

或者在我看来有点清洁:

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