SQL案例适用于不同的标准

时间:2013-11-13 15:06:02

标签: sql-server

我有一个查询,我试图从2012年和2013年拉动员工的发展评级:

SELECT Employee_ID, Meeting_Year, Meeting_Readiness_Rating
FROM  dbo.v_sc17_TMS_Data_Career_Meeting_Rating
GROUP BY Employee_ID, Meeting_Year, Meeting_Readiness_Rating

我正试图设置案例,因此它将2012年的评级分为一列而2013年则分为另一列。我希望它看起来像

Employee ID       2012 Meeting Rating        2013 Meeting Rating

即使他们确实在2012年拿了一个而不是在2013年,我仍然需要两者的数据,我很难搞清楚这一点。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

SELECT Employee_ID, 
    CASE Meeting_Year WHEN 2012 THEN Meeting_Readiness_Rating ELSE NULL END as [2012 Meeting Rating],
    CASE Meeting_Year WHEN 2013 THEN Meeting_Readiness_Rating ELSE NULL END as [2013 Meeting Rating]
FROM  dbo.v_sc17_TMS_Data_Career_Meeting_Rating
GROUP BY Employee_ID, Meeting_Year, Meeting_Readiness_Rating

答案 1 :(得分:1)

   SELECT Employee_ID, sum(r2012) as '2012 Meeting Rating', sum(r2013) as '2013 Meeting Rating' from 
    (SELECT Employee_ID, 
       CASE Meeting_Year WHEN 2012 THEN Meeting_Readiness_Rating ELSE 0 END as r2012,
        CASE Meeting_Year WHEN 2013 THEN Meeting_Readiness_Rating ELSE 0 END as r2013 FROM  dbo.v_sc17_TMS_Data_Career_Meeting_Rating ) GROUP BY Employee_ID

答案 2 :(得分:0)

SELECT  yr_2012.Employee_ID     
        ,yr_2012.Meeting_Readiness_Rating AS [2012_Meeting_Rating]
        ,yr_2013.Meeting_Readiness_Rating AS [2013_Meeting_Rating]
FROM    dbo.v_sc17_TMS_Data_Career_Meeting_Rating as yr_2012
        CROSS APPLY (
            SELECT  mr.Meeting_Readiness_Rating
            FROM    dbo.v_sc17_TMS_Data_Career_Meeting_Rating as mr
            WHERE   mr.Meeting_Year = '2013' AND
                    yr_2012.Employee_ID = mr.Employee_ID
        ) yr_2013
WHERE   Meeting_Year = '2012' ;