在多个表上的情况

时间:2018-04-19 10:02:13

标签: sql sql-server tsql

我的表格如下:

SELECT TOP 5 PlanningID, ActivityID, 
       [This Week - 2], [This Week - 1]
FROM [BI_Planning].[dbo].[tblPlanning] 

enter image description here

我希望结果如下:

enter image description here

下面的代码没有给出我想要的内容,但是 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用于多列?

1 个答案:

答案 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);

但是,我没有找到您的周列01背后的逻辑