gpt4 book ai didi

从创建日期开始按年龄范围分组的 SQL 查询

转载 作者:行者123 更新时间:2023-11-29 11:32:09 25 4
gpt4 key购买 nike

我想通过 sql 查询获取统计信息。我的 table 是这样的:

ID MATERIAL CREATEDATE DEPARTMENT
1 M1 10.10.1980 D1
2 M2 11.02.1970 D2
2 M3 18.04.1971 D3
.....................
.....................
.....................

我怎样才能得到这样的数据计数范围

DEPARTMENT AGE<10  10<AGE<20 20<AGE
D1 24 123 324
D2 24 123 324

最佳答案

假设 CREATEDATE 是一个日期列,在 PostgreSQL 中您可以使用 AGE功能:

select DEPARTMENT, age(CREATEDATE) as AGE
from Materials

使用 date_part 可以得到年龄。要以您想要的格式显示数据,您可以使用此 GROUP BY 查询:

select
DEPARTMENT,
sum(case when date_part('year', age(CREATEDATE))<10 then 1 end) as "age<10",
sum(case when date_part('year', age(CREATEDATE))>=10 and date_part('year', age(CREATEDATE))<20 then 1 end) as "10<age<20",
sum(case when date_part('year', age(CREATEDATE))>=20 then 1 end) as "20<age"
from
Materials
group by
DEPARTMENT

可以简化为:

with mat_age as (
select DEPARTMENT, date_part('year', age(CREATEDATE)) as mage
from Materials
)
select
DEPARTMENT,
sum(case when mage<10 then 1 end) as "age<10",
sum(case when mage>=10 and mage<20 then 1 end) as "10<age<20",
sum(case when mage>=20 then 1 end) as "20<age"
from
mat_age
group by
DEPARTMENT;

如果您使用的是 PostgreSQL 9.4,则可以使用 FILTER:

with mat_age as (
select DEPARTMENT, date_part('year', age(CREATEDATE)) as mage
from Materials
)
select
DEPARTMENT,
count(*) filter (where mage<10) as "age<10",
count(*) filter (where mage>=10 and mage<20) as "10<age<20",
count(*) filter (where mage>=20) as "20<age"
from
mat_age
group by
DEPARTMENT;

关于从创建日期开始按年龄范围分组的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34651030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com