I have the following code where I am trying to separate the birthdates of clients into generations and for some reason it is giving me a column name error, this is how I have always written my case when statements but now it appears to not be working. And I am getting an unable to parse query text error which I believe has something to do with the GenY portion of the code

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
有帮助吗?

解决方案

if those values (BabyBoomer,GenY) were string and not column, you need to wrap it with single quotes because they are string literals not identifiers.

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

UPDATE 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

其他提示

Looking at your query I thought that you could do as JW said and still simplify your query... because it seems you're using another clause when there's no need for that, since two clauses generates the same result. Oh, and we're still a bit far from 2964 year. :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

I think it could be your date strings or column names or both. Try to get them into ISO format (ie; yyyymmdd) and if BabyBoomer and GenY are not column names then you need mark them as string with '

Also CASE statement should return a 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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top