SQL trunc/group/order by dates (day/month/quarter/year) with sum skip dates with no data

前端 未结 3 454
温柔的废话
温柔的废话 2021-01-22 16:16

I involved in project where I need to build histogram by dates. Before me this done in Java code by tons of SQL queries to DB for each rectangles (date subregions).

I tr

3条回答
  •  感动是毒
    2021-01-22 17:06

    Try something like this (simplified example):

    with 
    months_int as
    (select trunc(min(inc_date), 'MM') min_month, trunc(max(inc_date), 'MM') max_month
     from data),
    months as
    (
      select add_months(min_month, level-1) mnth_date
      from months_int 
      connect by add_months(min_month, level-1)<= max_month
      )
    select  mnth_date, sum(cnt) 
    from data  right outer join months on trunc(inc_date, 'MM') = mnth_date
    group by mnth_date
    order by mnth_date
    

    Here is a sqlfiddle example

提交回复
热议问题