甲骨文:按十年分组数据

时间:2018-05-07 08:04:00

标签: sql oracle

我有一张客户表,其中包含以下详细信息:

DOB是Oracle中的日期数据类型

Customer ID   Name            DOB
1             Babu          20-07-1987
2             MohanLal      20-04-1962
3             Mammootty     20-04-1961

期望的结果:

Decade start    Decade end     No_of_customers
1960-01-01       1969-12-31            2
1980-01-01       1989-12-31            1

2 个答案:

答案 0 :(得分:2)

您可以尝试以下SQL查询:

 SELECT 
    substr(TO_CHAR(DOB,'YYYY-MM-DD'),1,3)||'0-01-01' as DECADE_START,
    substr(TO_CHAR(DOB,'YYYY-MM-DD'),1,3)||'9-12-31' as DECADE_END,
    count(1) AS NO_OF_CUSTOMERS
    FROM 
    customer_table
    group by 
    substr(TO_CHAR(DOB,'YYYY-MM-DD'),1,3)

答案 1 :(得分:0)

使用截断函数和正确的日期格式:

select 10*trunc(to_char(DOB,'yyyy')/10) "Decade", count(1) "No_of_customers"
  from tab
 group by 10*trunc(to_char(DOB,'yyyy')/10)
 order by 1;

我最近意识到你的最后一次编辑。关于这一点,您可以使用以下内容:

with t as
(
 select trunc(to_date(10*trunc(to_char(DOB,'yyyy')/10),'yyyy'),'year')   Decade_Start,
        trunc(to_date(10*ceil(to_char(DOB,'yyyy')/10),'yyyy'),'year')-1  Decade_End
   from tab
 )
 select t.*, count(1) No_of_customers 
   from t  
 group by Decade_Start, Decade_End
 order by 1;

SQL Fiddle Demo