基于月的oracle计数

时间:2012-10-22 21:47:06

标签: sql oracle

我正在尝试编写Oracle SQL。

我正在寻找类似的解决方案。请查看以下数据

start_date      end_date        customer 
01-01-2012      31-06-2012      a 
01-01-2012      31-01-2012      b  
01-02-2012      31-03-2012      c  

我想要该日期期间的客户数量。我的结果应该如下所示

Month   : Customer Count 
JAN-12  :  2 
FEB-12  :  2 
MAR-12  :  2 
APR-12  :  1 
MAY-12  :  1 
JUN-12  :  1 

2 个答案:

答案 0 :(得分:1)

一种选择是在另一个查询中单独生成月份并将其加入到您的数据表中(请注意,我假设您打算将客户A的结束日期定为2012年6月30日,因为没有6月31)。

SQL> ed
Wrote file afiedt.buf

  1  with mnths as(
  2    select add_months( date '2012-01-01', level - 1 ) mnth
  3      from dual
  4   connect by level <= 6 ),
  5  data as (
  6    select date '2012-01-01' start_date, date '2012-06-30' end_date, 'a' customer from dual union all
  7    select date '2012-01-01', date '2012-01-31', 'b' from dual union all
  8    select date '2012-02-01', date '2012-03-31', 'c' from dual
  9  )
 10  select mnths.mnth, count(*)
 11    from data,
 12         mnths
 13   where mnths.mnth between data.start_date and data.end_date
 14   group by mnths.mnth
 15*  order by mnths.mnth
SQL> /

MNTH        COUNT(*)
--------- ----------
01-JAN-12          2
01-FEB-12          2
01-MAR-12          2
01-APR-12          1
01-MAY-12          1
01-JUN-12          1

6 rows selected.

答案 1 :(得分:1)

WITH TMP(monthyear,start_date,end_date,customer) AS (
  select LAST_DAY(start_date),
         CAST(ADD_MONTHS(start_date, 1) AS DATE),
         end_date,
         customer
  from data
  union all
  select LAST_DAY(start_date),
         CAST(ADD_MONTHS(start_date, 1) AS DATE),
         end_date,
         customer
  from TMP
  where LAST_DAY(end_date) >= LAST_DAY(start_date)
)
SELECT TO_CHAR(MonthYear, 'MON-YY') TheMonth,
       Count(Customer) Customers
FROM TMP
GROUP BY MonthYear
ORDER BY MonthYear;

SQLFiddle