SQL Server 2008 R2 - 将多行减少为一行

时间:2015-01-15 14:40:44

标签: sql-server sql-server-2008-r2 case select-case

我需要让我的数据在一行中显示 个人是否在过去3年内有'已完成'特定课程。

这是我的现有表& 所需的表(希望此链接有效,因为我无法发布图片!): http://i.stack.imgur.com/c8oJO.png

我试过这段代码:

SELECT DISTINCT
EN,
(First_Name + ' ' + Last_Name) as Name,

First_Aid = CASE
WHEN Course = 'First Aid' 
and Status = 'Finished'
and Course_Start_Date > DATEADD(day, -1095, GETDATE())
THEN 'F'
ELSE 'Nope'
END,

Manual_Handling = CASE
WHEN Course = 'Manual Handling'
and Status = 'Finished'
and Course_Start_Date > DATEADD(day, -1095, GETDATE())
THEN 'F'
ELSE 'Nope'
END,

Fire_Safety = CASE
WHEN Course = 'Fire Safety'
and Status = 'Finished'
and Course_Start_Date > DATEADD(day, -1095, GETDATE())
THEN 'F'
ELSE 'Nope'
END
into MyTraining
FROM Learning_History`

这会产生准确的结果,但每个CASE语句都有一个单独的行(加上一个包含所有“Nope”结果的额外行)。所以我尝试了这段代码:

SELECT 
EN,
(First_Name + ' ' + Last_Name) as Name,

First_Aid =MAX(CASE
WHEN Course = 'First Aid' 
and Status = 'Finished'
and Course_Start_Date > DATEADD(day, -1095, GETDATE())
THEN 'F'
ELSE 'Nope'
END),

Manual_Handling =MAX(CASE
WHEN Course = 'Manual Handling' 
and Status = 'Finished'
and Course_Start_Date > DATEADD(day, -1095, GETDATE())
THEN 'F'
ELSE 'Nope'
END),

Fire_Safety =MAX(CASE
WHEN Course = 'Fire Safety' 
and Status = 'Finished'
and Course_Start_Date > DATEADD(day, -1095, GETDATE())
THEN 'F'
ELSE 'Nope'
END)

into MyTraining
FROM Learning_History

Group By EN,First_Name, Last_Name

此代码生成1行 - 但所有结果都是'Nope'。

我真的不太了解这个(大部分代码只是用Google搜索),因为我是SQL的初学者(所以我可能做了一些简单的错误)。我认为枢轴表可能是要走的路 - 但我无法理解它们......

1 个答案:

答案 0 :(得分:0)

您可以使用PIVOT或案例和小组来完成,就像您正在尝试一样。

PIVOT示例:

select
    EN,
    [First Aid],
    [Manual Handling],
    [Fire Safety]
from (
    select
        [EN],
        [Course],
        [Status]
    from (
        select
            ROW_NUMBER() OVER (
                PARTITION BY
                    EN,Course
                ORDER BY
                    Course_Start_Date
            ) rID,
            *
        from (
            select
            *
            from (
                values
                    (1,'First Aid','1999-06-22','Finished'),
                    (1,'First Aid','2013-02-19','Finished'),
                    (1,'Manual Handling','2014-02-10','Cancelled'),
                    (1,'Manual Handling','2014-03-20','Finished'),
                    (1,'Fire Safety','2099-07-29','Finished'),
                    (1,'Fire Safety','2014-11-19','No Show')
            ) myTable ([EN],[Course],[Course_Start_Date],[Status])
        ) myTable
    )T
    where
        rID = 1
) S
PIVOT (
    MAX(Status) FOR Course IN ([First Aid],[Manual Handling],[Fire Safety])
) PVT

PS:我假设EN是PRIMARY KEY

编辑:再试一次,)