2015-01-15 289 views
0

我有一张表格“学生”,其中包含学生的“姓名”和“出生日期”。SQL组学生按年龄从出生日期起

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

a。 b。10-12
b。 13-14
c。 d。15-16 d。 > = 17

所以它会出现

a。保罗,彼得玛丽
b。约翰,威廉

我该怎么办呢?

到目前为止,我有:

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

什么不工作?你有错误吗?另外,什么DBMS? – 2015-01-15 17:16:14

+0

我正在使用Management Studio。 – CompilerSaysNo 2015-01-15 17:19:41

+0

那么DBMS会是SQL Server呢?你可以相应标签吗? – 2015-01-15 17:20:49

回答

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; 
相关问题