我的表格如下:
SELECT TOP 5 PlanningID, ActivityID,
[This Week - 2], [This Week - 1]
FROM [BI_Planning].[dbo].[tblPlanning]
我希望结果如下:
下面的代码没有给出我想要的内容,但是 CASE 表达式应该给我 201814 和 201815 ,但它没有:/
SELECT TOP 5 PlanningID,
ActivityID,
CASE WHEN [This Week - 2] IN ('TRUE','FALSE')-- OR [This Week - 2] = 'FALSE'
THEN (SELECT LEFT(CONVERT(VARCHAR(10),GETDATE(),120),4) +
CAST((DATEPART(ISOWK,GETDATE()) - 2) AS NVARCHAR(2)))
WHEN [This Week - 1] IN ('TRUE','FALSE')-- OR [This Week - 1] = 'FALSE'
THEN (SELECT LEFT(CONVERT(VARCHAR(10),GETDATE(),120),4) +
CAST((DATEPART(ISOWK,GETDATE()) - 1) AS NVARCHAR(2)))
END AS YearWeek
FROM [BI_Planning].[dbo].[tblPlanning]
我是否需要使用某种Cross join
以及如何将case when
用于多列?
答案 0 :(得分:1)
使用apply
运算符
SELECT p.PlanningID, p.ActivityID,
(CASE WHEN t.id = 2 AND t.Weeks IN (1, 0)
THEN '201814' WHEN t.id = 1 AND t.Weeks IN (1, 0)
THEN '201815' END) AS ThisWeek
FROM [BI_Planning].[dbo].[tblPlanning] p
CROSS APPLY (VALUES (2, [This Week - 2]), (1, [This Week - 1])) t(Id, Weeks);
但是,我没有找到您的周列0
或1
背后的逻辑