如何编写此 SQL 服务器语法以根据同一 table 中其他 2 列的值更新列

How to write this SQL Server syntax to update a column based on the values of 2 other columns in that same table

我正在使用 SQL Server 2014,我需要编写一个 SQL 查询来更新我的 DateDimension Table.

中的列(称为 ToY)

这是我的 DateDimension Table 的摘录:

Day      Month     Year         Date          ToY
 1         11       2014     2014-11-01       NULL
 2         11       2014     2014-11-02       NULL

我需要根据这个逻辑更新那个 ToY 列:

对于 2014 年 11 月至 2015 年 10 月之间的所有日期,ToY 将为 'ToY 14-15',对于 2015 年 11 月至 2015 年 10 月之间的所有日期,ToY 将为 'ToY 15-16'。

例如:如果月 = 11 且年 = 2014,则 ToY = 'ToY 14-15'

我试过这段 SQL 代码,但它不起作用:

 UPDATE DateDimension

 SET ToY = CASE Month+Year

 WHEN 112014 THEN 'ToY 14-15'

 ELSE ToY

 END
 GO

我进行了搜索,发现我可以将第三行写为: 当月 = 11 且年 = 2014 时 'ToY 14-15'

但我对 CASE 语句后的内容感到困惑:

Set ToY = CASE ??

案例中可以有布尔表达式,所以:

update DateDimension
set ToY = case when month = 11 and year = 2014 then 'ToY 14-15' 
          else ToY end

2014-11 年获得“14-15”的逻辑尚不清楚。也许您每个月都在增加“4”。

无论如何,这给出了如何根据 yearmonth 列进行更新的想法:

update DateDimension
    set ToY = 'ToY ' + right('00' + cast(year as varchar(255)), 2) + '-' +
              right('00' + cast(month + 4 as varchar(255)), 2);

这使用了一些函数,但希望能使我的思路清晰:

UPDATE DateDimension

SET ToY = 'ToY ' + 
    CONVERT(char(2),DATEADD(month,-10,[Date]),12) + '-' +
    CONVERT(char(2),DATEADD(month,2,[Date]),12)

DATEADD(month,-10,... - 对于早于 11 月的任何日期,将此日期移至去年。 DATEADD(month,2,... - 对于晚于 10 月的任何日期,将此日期移至明年。合起来,这些要么 select 去年和今年(早于 11 月),要么今年和明年。

CONVERT(char(2),<date>,12) - 在 style yymmdd 中将日期转换为字符串 - 但因为我要求 char(2),只有前 2 个字符被保留。

UPDATE DateDimension
SET ToY = 
  CASE WHEN Month >= 11 then 
    'ToY '+cast( right(year,2) as varchar(2))+'-'+cast(right(year,2)+1 as varchar(2))
   WHEN Month < 11 then 
    'ToY '+cast( right(year,2)-1 as varchar(2))+'-'+cast(right(year,2) as varchar(2))

  ELSE ToY
  END

假设年份是数值,如果年份是字符串则使用子字符串。