给定出生年份(SQL)如何将人们分为年龄段

时间:2019-11-12 19:07:59

标签: sql case sql-server-2014

考虑到birth_year和personal_id,我想创建var“ age”,然后将personal_id分组为截至2018年的年龄段(范围)。

我尝试过的事情:

SELECT personal_id, (2018 - birth_year) AS age
FROM mydatabase
WHERE birth_year is not null
GROUP BY CASE
    WHEN age between 18 and 24 THEN '18-24'
    WHEN age between 25 and 34 THEN '25-34'
    WHEN age between 35 and 44 THEN '35-44'
    WHEN age between 45 and 54 THEN '45-54'
    WHEN age between 55 and 64 THEN '55-64'
    WHEN age > 64 THEN '65+'
    END

我收到一个错误消息,说“ age”不是列名。我假设CASE语句可能需要嵌套,就像这样:

SELECT personal_id
FROM
(SELECT personal_id, (2018 - birth_year) as age,
CASE
    WHEN age between 18 and 24 THEN '18-24'
    WHEN age between 25 and 34 THEN '25-34'
    WHEN age between 35 and 44 THEN '35-44'
    WHEN age between 45 and 54 THEN '45-54'
    WHEN age between 55 and 64 THEN '55-64'
    WHEN age > 64 THEN '65+'
ELSE 0
END AS age_group
FROM mydatabase
).

理想的方法是先创建“年龄”变量,然后再进行分类。

我希望这足够清楚。谢谢!

2 个答案:

答案 0 :(得分:0)

使用APPLY

SELECT agegrp, COUNT(*)
FROM mydatabase d CROSS APPLY
     (VALUES (2018 - birth_year)) v1(age) CROSS APPLY
     (VALUES (CASE WHEN v1.age between 18 and 24 THEN '18-24'
                   WHEN v1.age between 25 and 34 THEN '25-34'
                   WHEN v1.age between 35 and 44 THEN '35-44'
                   WHEN v1.age between 45 and 54 THEN '45-54'
                   WHEN v1.age between 55 and 64 THEN '55-64'
                   WHEN v1.age > 64 THEN '65+'
              END)
     ) v(agegrp)
WHERE birth_year is not null
GROUP BY agegrp;

我将您的查询更改为聚合查询,这样才有意义。

答案 1 :(得分:0)

不允许使用内联别名

SELECT personal_id, CASE
WHEN (2018 - birth_year) between 18 and 24 THEN '18-24'
WHEN (2018 - birth_year) between 25 and 34 THEN '25-34'
WHEN (2018 - birth_year) between 35 and 44 THEN '35-44'
WHEN (2018 - birth_year) between 45 and 54 THEN '45-54'
WHEN (2018 - birth_year) between 55 and 64 THEN '55-64'
WHEN (2018 - birth_year) > 64 THEN '65+' AS age_grop
FROM mydatabase
WHERE birth_year is not null
GROUP BY CASE
    WHEN (2018 - birth_year) between 18 and 24 THEN '18-24'
    WHEN (2018 - birth_year) between 25 and 34 THEN '25-34'
    WHEN (2018 - birth_year) between 35 and 44 THEN '35-44'
    WHEN (2018 - birth_year) between 45 and 54 THEN '45-54'
    WHEN (2018 - birth_year) between 55 and 64 THEN '55-64'
    WHEN (2018 - birth_year) > 64 THEN '65+'
    END,personal_id