我需要让我的数据连续显示一个人在过去 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 行 - 但所有结果都是“不”。
我不太了解这个(只是用谷歌搜索了大部分代码),因为我是 SQL 的初学者(所以我可能犯了一些简单的错误)。我认为数据透视表可能是要走的路 - 但我无法理解它们......