SQL Server 2008 R2 – 将多行缩减为一行

SQL Server 2008 R2 – Reducing multiple rows into one

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

这是我的现有的table&想要的table(希望这个link有用因为我还不能 post 图片!): 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 语句都有一个单独的行(加上一个包含所有“否”结果的额外行)。所以我试过这段代码:

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 的初学者(所以我可能犯了一些简单的错误)。我认为 pivot tables 可能是可行的方法 - 但我无法理解它们...

您可以像您尝试的那样使用 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 是主键

编辑:再试一次,)