如何在oracle上分隔年份范围

How to separate range of year on oracle

我正在使用 db oracle,我需要在 return 日期范围内创建一个查询。例如:

假设我有一个这样的字段:

我需要获取此日期并将年份范围应用到 return 某些事情,例如:

|'0-5'|'6-10'|'11-15'|... 
| 10  |  35  |   20  |...

其中每个范围包含该年龄范围内的人数。

我尝试使用 SELECT CASE...

SELECT CASE 
    WHEN DATE_BORN <= DATE_BORN + 5 THEN '0 - 5
    WHEN DATE_BORN >= DATE_BORN + 6 AND DATE_BORN <= 10 THEN '6 - 10'
        END AS AGE_RANGE,
    COUNT(*)
FROM MY_TABLE
GROUP BY 1

所以我看到这种方式只改变天而不是年。

如何编写此查询?

这是条件聚合:

SQL> with test (date_born) as
  2    (select date '2000-05-12' from dual union all
  3     select date '2001-05-12' from dual union all
  4     select date '2012-05-12' from dual union all
  5     select date '2013-05-12' from dual union all
  6     select date '2004-05-12' from dual union all
  7     select date '2008-05-12' from dual union all
  8     select date '2009-05-12' from dual union all
  9     select date '2001-05-12' from dual union all
 10     select date '2012-05-12' from dual union all
 11     select date '2001-05-12' from dual union all
 12     select date '2004-05-12' from dual union all
 13     select date '2005-05-12' from dual
 14    )
 15  select
 16    sum(case when extract (year from date_born) between 2000 and 2005 then 1 else 0 end) as "2000 - 2005",
 17    sum(case when extract (year from date_born) between 2006 and 2010 then 1 else 0 end) as "2006 - 2010",
 18    sum(case when extract (year from date_born) between 2011 and 2015 then 1 else 0 end) as "2011 - 2015"
 19  from test;

2000 - 2005 2006 - 2010 2011 - 2015
----------- ----------- -----------
          7           2           3

SQL>

这是一个动态的方法(使用上面的示例 table)

首先,我认为将范围设置为行而不是列更容易,更容易设置可能会更改的各种日期。

其次,您的第一个分组是 6 年,所以我将其更改为 5 年系列:

with test (date_born) as
 (select date '2000-05-12' from dual union all
  select date '2001-05-12' from dual union all
  select date '2012-05-12' from dual union all
  select date '2013-05-12' from dual union all
  select date '2004-05-12' from dual union all
  select date '2008-05-12' from dual union all
  select date '2009-05-12' from dual union all
  select date '2001-05-12' from dual union all
  select date '2012-05-12' from dual union all
  select date '2001-05-12' from dual union all
  select date '2004-05-12' from dual union all
  select date '2005-05-12' from dual
  )
  ,mydata AS (
SELECT 
  (SELECT min(extract(YEAR FROM date_born)) FROM test)+((LEVEL-1)*5)dt1 
  ,(SELECT min(extract(YEAR FROM date_born)) FROM test)+((LEVEL-1)*5)+4 dt2
FROM dual CONNECT BY LEVEL*5 <= 
  (SELECT max(extract(YEAR FROM date_born))-min(extract(YEAR FROM date_born)) FROM test)+5) 
SELECT d.*, count(t.date_born) cnt FROM mydata d 
LEFT JOIN test t ON extract(YEAR FROM date_born) BETWEEN d.dt1 AND d.dt2
GROUP BY dt1, dt2
ORDER BY dt1;

你得到这个作为你的解决方案

DT1     DT2     CNT
2000    2004    6
2005    2009    3
2010    2014    3

解决方案基本上是从日期中提取年份,找到此数据集的 min/max,使用 connect 获取中间的所有年份,然后加入以计算匹配记录