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

时间:2016-01-07 09:04:46

标签: sql postgresql

我想用sql查询获取统计信息。我的桌子是这样的:

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

3 个答案:

答案 0 :(得分:3)

假设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;

答案 1 :(得分:2)

以下解决方案假定您的CREATEDATE列存在某种有效的Postgres日期类型。如果不是这种情况,并将其存储为文本,则首先必须将其转换为日期才能使查询生效。

SELECT DEPARTMENT,
    SUM(CASE WHEN DATEDIFF(year, CREATEDATE, now()::date) < 10 THEN 1 ELSE 0 END) AS "AGE<10",
    SUM(CASE WHEN DATEDIFF(year, CREATEDATE, now()::date) >= 10 AND
             DATEDIFF(year, CREATEDATE, now()::date) < 20 THEN 1 ELSE 0 END) AS "10<AGE<20",
    SUM(CASE WHEN DATEDIFF(year, CREATEDATE, now()::date) >= 20 THEN 1 ELSE 0 END) AS "20<AGE"
FROM Materials
GROUP BY DEPARTMENT

答案 2 :(得分:2)

您可以使用extract(year FROM age(createdate))来获取确切的年龄

select extract(year FROM age(timestamp '01-01-1989')) age

会给你

结果:

age
---
 27

因此您可以使用以下select语句来获得所需的输出:

 SELECT dept
    ,sum(CASE  WHEN age < 10THEN 1 END) "age<10"
    ,sum(CASE  WHEN age >= 10  AND age < 20 THEN 1 END) "10<age<20"
    ,sum(CASE WHEN age >= 20 THEN 1 END) "20<age"
FROM (
    SELECT dept,extract(year FROM age(crdate)) age
    FROM dt
    ) t
GROUP BY dept

如果您不想使用子选择,请使用此选项。

SELECT dept
    ,sum(CASE  WHEN extract(year FROM age(crdate)) < 10THEN 1 END) "age<10"
    ,sum(CASE  WHEN extract(year FROM age(crdate)) >= 10  AND extract(year FROM age(crdate)) < 20 THEN 1 END) "10<age<20"
    ,sum(CASE WHEN extract(year FROM age(crdate)) >= 20 THEN 1 END) "20<age"
FROM dt
GROUP BY dept