2

我正在尝试编写 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 
4

2 回答 2

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

于 2012-10-22T22:13:48.500 回答
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.
于 2012-10-22T22:05:42.870 回答