SQL Server 2012中的CASE函数收到错误消息

时间:2017-01-21 15:58:33

标签: sql sql-server sql-server-2012

有人可以帮帮我吗?

我正在尝试使用CASE函数,如下面的错误消息说

  

消息156关键字'CASE'附近的语法不正确。

谢谢,

select distinct 
    FiscalYear 
    case
       when FiscalYear = '2014' 
          then 'FY2014/2015'
       when FiscalYear = '2015' 
          then 'FY2015/2016'
       when FiscalYear = '2016' 
          then 'FY2016/2017'
       else 'FY2017/2018'
    end
from  
    DimDate
order by 
    FiscalYear

2 个答案:

答案 0 :(得分:2)

FiscalYear后缺少逗号。

SELECT DISTINCT FiscalYear, --here
                CASE
                  WHEN FiscalYear = '2014' THEN 'FY2014/2015'
                  WHEN FiscalYear = '2015' THEN 'FY2015/2016'
                  WHEN FiscalYear = '2016' THEN 'FY2016/2017'
                  ELSE 'FY2017/2018'
                END
FROM   DimDate
ORDER  BY FiscalYear

但是我们可以像这样简化您的查询

SELECT DISTINCT FiscalYear,
                CASE
                  WHEN FiscalYear IN ( '2014', '2015', '2016' ) THEN Concat('FY', FiscalYear, '/', FiscalYear + 1)
                  ELSE 'FY2017/2018'
                END
FROM   DimDate
ORDER  BY FiscalYear 

答案 1 :(得分:0)

我认为不需要CASE。您需要编辑逻辑多年才能跟进。

Declare @YourTable table (FiscalYear varchar(10))
Insert Into @YourTable values
('2014'),
('2015'),
('2016'),
('2017')

Select Distinct FiscalYear = concat('FY',FiscalYear,'/',1+FiscalYear)
 From  @YourTable

返回

FiscalYear
FY2014/2015
FY2015/2016
FY2016/2017
FY2017/2018