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

1つのオプションは、別のクエリで月を個別に生成し、それをデータテーブルに結合することです(6月31日がないため、顧客Aの終了日を2012年6月30日と想定していることに注意してください)。

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 に答える
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;

SQLフィドル

于 2012-10-22T22:13:48.500 に答える