2015-01-15 74 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; 
相關問題