SQL 从出生日期起按年龄对学生进行分组
SQL group students by age from date of birth
我有一个 table "student",其中包含学生的 "name" 和 "DOB"。
我想将学生分为以下几组:
一个。 10-12
b. 13-14
C。 15-16
d. >= 17
所以它会出现
一个。保罗,彼得玛丽
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。
非常感谢。
以下查询可能会为您提供所需的结果。首先,年龄是确定的。 (我在 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;
我有一个 table "student",其中包含学生的 "name" 和 "DOB"。
我想将学生分为以下几组:
一个。 10-12
b. 13-14
C。 15-16
d. >= 17
所以它会出现
一个。保罗,彼得玛丽
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。
非常感谢。
以下查询可能会为您提供所需的结果。首先,年龄是确定的。 (我在 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;