在Oracle中按2个日期分组

时间:2018-06-18 10:26:17

标签: sql oracle

我在表格中有以下示例数据: -

Property_ID Start_Date  Status  Sale_Date
110         01/01/2017  Sold    01/02/2017
111         01/01/2017  Sold    05/02/2017
112         01/01/2017  Sold    31/12/2017
113         01/01/2017  Sold    31/12/2017
114         01/02/2017  Sold    18/04/2017
115         01/02/2017  Sold    18/04/2017
116         01/02/2017  Sold    18/12/2017

On Oracle是否可以一起输出基于Start_date和Sale_Date的数据,其中Sale_Date距离Start_Date不到6个月?因此,样本数据的预期输出将是: -

        Active  Six_months
Jan 17  4       2
Feb 17  3       2

2 个答案:

答案 0 :(得分:2)

嗯。嗯。 。 。您可以使用条件聚合,但需要生成月份列表:

select to_char(month_start, 'YYYY-MM') as yyyymm,
       count(t.property_id) as num_active,
       sum(case when sale_date < add_months(start_date, 6) then 1 else 0
           end) as num_sold_within_six_months
from (select date '2017-01-01' as month_start, date '2017-02-01' as month_end from dual union all
      select date '2017-02-01' as as month_start, date '2017-03-01' as month_end from dual
     ) d left join
     t
     on start_date >= month_start and start_date < month_end
group by to_char(sale_date, 'YYYY-MM')
order by yyyymm;

严格来说,如果所有月份都有数据,您就不需要月份列表:

select to_char(sale_date, 'YYYY-MM') as yyyymm,
       count(t.property_id) as num_active,
       sum(case when sale_date < add_months(start_date, 6) then 1 else 0
           end) as num_sold_within_six_months
from t
group by to_char(sale_date, 'YYYY-MM')
order by yyyymm;

答案 1 :(得分:0)

你走了:

Select trunc(Start_Date,'MM'),
       count(*) as "Active",
       SUM(case when MONTHS_BETWEEN(Sale_Date,Start_Date) <= 6 THEN 1 ELSE 0) as Six_months
From Table
Group by trunc(start_date,'MM');

编辑:错误的截断类型,应该是trunc(Start_Date,&#39; MM&#39;)而不是trunc(Start_Date)