【问题标题】:SQL Server- if else/case when statementSQL Server - if else/case when 语句
【发布时间】:2018-03-12 17:11:06
【问题描述】:

我在我的选择查询中写了一个 case 语句,如下所示。我不确定 SQL Server 中 If else 的语法,并且我想使用“as”来命名列,但它会抛出错误,说明“as”附近的语法错误。请帮忙。 T

select 
    a.account_id as [Account Id],
    substring(a.account_id,1,3) as [Company ID],
    substring(a.account_id,4,6) as [Account No],
    substring(a.account_id,10,5) as [Cost Center],
    b.amount as Amount,
    b.period as Period,
    getdate() as SysDate,
    format(getdate(), 'mm/dd/yyyy') as SYSDtText,
    substring('SYSDtText',1,2) as [Current Period],
    b.year_budget as [Year Budget],
    substring('SYSDtText', 7, 4 ) as SysDtYearText,
    case 
       when Period <= 'Current Period' 
          then 'include' 
          else '' 
    as [Period Include Flag], 
    a.description as [Description]
from 
    period_summary b
inner join 
    account a on b.account_id = a.account_id;

【问题讨论】:

  • 您在else ''as 之间错过了end

标签: sql-server sql-server-2008 if-statement sql-server-2012 case-when


【解决方案1】:

你错过了一个“结束”

正确:

CASE WHEN Period<='Current Period' then 'include' else '' end as [Period Include Flag]

【讨论】:

  • 工作。非常感谢!
【解决方案2】:

我认为您需要更改此行:

CASE WHEN Period<='Current Period' then 'include' else '' as [Period Include Flag], 

到这里:

CASE WHEN Period <= substring('SYSDtText',1,2) then 'include' else '' end as [Period Include Flag], 

目前您正在将 [Period] 与字符串文字“Current Period”进行比较——我认为这不是您打算做的,因为您的查询中有一个名为 [Current Period] 的列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    相关资源
    最近更新 更多