1

我有以下代码,我试图将客户的生日分成几代人,由于某种原因,它给了我一个列名错误,这就是我一直写我的 case when 语句的方式,但现在它似乎不起作用。而且我遇到了无法解析查询文本错误,我认为这与代码的 GenY 部分有关

SELECT Birthdate, (
    CASE WHEN Birthdate <= '12/31/2964' THEN BabyBoomer 
         WHEN Birthdate >= '1/1/1980' THEN GenY 
         WHEN Birthdate >='1/1/1965' AND <='12/31/1979' THEN GenY 
         ELSE NULL 
    END) AS Generation
FROM  dbo.All_Employee_Detail
GROUP BY Birthdate
4

3 回答 3

3

如果这些值 ( BabyBoomer,GenY ) 是字符串而不是列,则需要用单引号将其括起来,因为它们是字符串文字而不是标识符。

SELECT Birthdate, 
      (CASE WHEN Birthdate <= '12/31/2964' 
              THEN 'BabyBoomer' 
            WHEN Birthdate >= '1/1/1980'  
              THEN 'GenY' 
            WHEN Birthdate BETWEEN '1/1/1965' AND '12/31/1979' 
              THEN 'GenY' 
            ELSE NULL 
       END) AS Generation
FROM  dbo.All_Employee_Detail
GROUP BY Birthdate

更新 1

SELECT Birthdate, 
      (CASE WHEN Birthdate BETWEEN '1/1/1980' AND '12/31/2964' 
              THEN 'BabyBoomer' 
            WHEN Birthdate BETWEEN '1/1/1965' AND '12/31/1979' 
              THEN 'GenY' 
            ELSE NULL 
       END) AS Generation
FROM  dbo.All_Employee_Detail
GROUP BY Birthdate
于 2013-02-28T14:33:13.610 回答
0

我认为这可能是您的日期字符串或列名或两者兼而有之。尝试将它们放入ISO format(ie; yyyymmdd) 并且如果BabyBoomer并且GenY不是列名,那么您需要将它们标记为字符串'

另外CASE声明应该返回一个single data type.

SELECT Birthdate, (
    CASE WHEN Birthdate >= '19650101' AND Birthdate <= '19800101' THEN 'GenY' 
         WHEN Birthdate >  '19800101' AND Birthdate <= '29641231' THEN 'BabyBoomer'
         ELSE NULL 
    END) AS Generation
FROM  dbo.All_Employee_Detail
GROUP BY Birthdate
于 2013-02-28T14:42:04.310 回答
0

查看您的查询,我认为您可以按照 JW 所说的那样做并且仍然简化您的查询......因为看起来您在不需要时使用了另一个子句,因为两个子句会产生相同的结果。哦,我们离 2964 年还有点远。:p

    SELECT Birthdate, 
          (CASE WHEN Birthdate <= '12/31/1964' 
                  THEN 'BabyBoomer' 
                WHEN Birthdate > '12/31/1964'
                  THEN 'GenY' 
                ELSE NULL 
           END) AS Generation
    FROM  dbo.All_Employee_Detail
    GROUP BY Birthdate
于 2013-02-28T14:53:12.833 回答