以下Case语句无法正常工作 - 将所有结果生成为' i' (声明中的' Else'部分)。 如果我注释掉 Else 部分代码可以正常工作,那么在符合条件的情况下产生NULL。 任何想法为什么会这样? ELSE不受支持吗?我确定我在Case声明中使用了Else(但从未使用和)?
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 'i'
END),
Manual_Handling =MAX(CASE
WHEN Course = 'Manual Handling'
and Status = 'Finished'
and Course_Start_Date > DATEADD(day, -1095, GETDATE())
THEN 'F'
ELSE 'i'
END),
Fire_Safety =MAX(CASE
WHEN Course = 'Fire Safety'
and Status = 'Finished'
and Course_Start_Date > DATEADD(day, -1095, GETDATE())
THEN 'F'
ELSE 'i'
END)
into MyTraining
FROM Learning_History
Group By EN,First_Name, Last_Name
答案 0 :(得分:2)
正如GSerg评论的那样,你问的是错误的。您可能希望使用这样的查询:
Fire_Safety =MAX(CASE
WHEN Course = 'Fire Safety'
and Status = 'Finished'
and Course_Start_Date > DATEADD(day, -1095, GETDATE())
THEN Course_Start_Date
ELSE null
END)
这将为您提供最近的消防安全课程,或null
如果没有满足条件的话。然后,如果需要,您可以在case
附近另外max
根据返回的值返回T
或F
或任何您想要的内容。或者不是,在任何一种情况下都不清楚你想要发生什么:)
答案 1 :(得分:0)
我认为你想在聚合之外将作业拉到I和F.这是一种方法:
SELECT EN,
(First_Name + ' ' + Last_Name) as Name,
(CASE WHEN SUM(CASE WHEN Course = 'First Aid' and Status = 'Finished' and Course_Start_Date > DATEADD(day, -1095, GETDATE())
THEN 1 ELSE 0 END) > 0
THEN 'F' ELSE 'I'
END) as First_Aid,
(CASE WHEN SUM(CASE WHEN course = 'Manual Handling' and Status = 'Finished' and Course_Start_Date > DATEADD(day, -1095, GETDATE()) > 0
THEN 1 ELSE 0 END) > 0
THEN 'F' ELSE 'I'
END) as Manual_Handling,
(CASE WHEN SUM(CASE WHEN Course = 'Fire Safety' and Status = 'Finished' and Course_Start_Date > DATEADD(day, -1095, GETDATE())
THEN 1 ELSE 0 END) > 0
THEN 'F'
ELSE 'i'
END) as Fire_Safety
into MyTraining
FROM Learning_History
Group By EN, First_Name, Last_Name