将SQL子查询与case语句一起使用时的问题

时间:2018-09-26 14:46:49

标签: sql sql-server

    select Firstname,LastName,age, case
    when age < 40 and age >= 25 then 'Young' 
    when age < 60 and age >= 40 then 'No More Young'
    when age >= 60 then 'Retired'
    else 'Dont Care'
    END as flag
    from (select FirstName,LastName,DATEDIFF(year,2018-08-26,BirthDate) as age from ContosoRetailDW.dbo.DimCustomer)

我在执行代码时遇到问题, ')'附近的语法不正确。

我现在正在学习SQL,因此将不胜感激。

2 个答案:

答案 0 :(得分:3)

问题不是case表达式。您缺少子查询的表别名。此外,日期常数必须用单引号引起来:

select Firstname, LastName, age,
       (case when age < 40 and age >= 25 then 'Young' 
             when age < 60 and age >= 40 then 'No More Young'
             when age >= 60 then 'Retired'
             else 'Dont Care'
        end) as flag
from (select FirstName, LastName, DATEDIFF(year, '2018-08-26', BirthDate) as age
      from ContosoRetailDW.dbo.DimCustomer
     ) c;

您可以通过确认条件按顺序求值来简化case逻辑:

select Firstname, LastName, age,
       (case when age >= 25  and age < 40 then 'Young' 
             when age < 60 then 'No More Young'
             when age >= 60 then 'Retired'
             else 'Dont Care'
        end) as flag
from (select FirstName, LastName, DATEDIFF(year, '2018-08-26', BirthDate) as age
      from ContosoRetailDW.dbo.DimCustomer
     ) c;

这只是一个简单的映射,只映射了三个范围。

答案 1 :(得分:0)

您应该只在查询末尾添加“作为客户”。原因是,每个子查询都必须有一个别名。 提供其他所有方法都是正确的(我不确定此DATEDIFF版本)应该可以正常工作。