SQL group学生按年龄从出生日期开始

时间:2015-01-15 17:14:25

标签: sql sql-server datediff

我有一张桌子"学生"以学生的名字为特色"和" DOB"。

我想将学生分成以下几组:

一个。 10-12
湾13-14
C。 15-16 d。 > = 17

所以它会出现

一个。保罗,彼得玛丽 湾约翰,威廉 等

我该怎么做?

到目前为止,我有:

 select  case
            when  age between 10 and 12 then a
            when  age between 13 and 14 then b
            when  age between 15 and 16 then c
            when  age >= 17 then d

    from    (
            SELECT  ROUND(DATEDIFF(Cast(CURRENT_TIMESTAMP() as Date),
                        Cast(birthday as Date)) / 365, 0) as age
            FROM    db.student 

但似乎无法理解它。

我正在使用Management Studio。

非常感谢提前。

1 个答案:

答案 0 :(得分:2)

以下查询可能会为您提供所需的结果。首先,确定年龄。 (我在DATEDIFF函数中添加了日期格式 - 日期 - 。然后,确定年龄类别。

WITH ages AS
(
SELECT
    name,
    ROUND(DATEDIFF(day, Cast(CURRENT_TIMESTAMP() as Date), Cast(birthday as Date)) / 365, 0) as age
FROM db.student
)
SELECT
    name,
    case
                    when  age between 10 and 12 then a
                    when  age between 13 and 14 then b
                    when  age between 15 and 16 then c
                    when  age >= 17 then d
    end as age_category
FROM ages
ORDER BY name;