Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need to create your list of dates first; either by creating a <a href="https://stackoverflow.com/questions/8374959/how-to-populate-calendar-table-in-oracle">calender table</a> or by using the <a href="http://docs.oracle.com/cd/E11882_01/server.112/e26088/queries003.htm#SQLRF52332" rel="nofollow noreferrer">CONNECT BY</a> syntax.</p> <pre><code>select to_date('01-01-2012','DD-MM-YYYY') + level - 1 from dual connect by level &lt;= to_date('31-12-2012','DD-MM-YYYY') - to_date('01-01-2012','DD-MM-YYYY') + 1 </code></pre> <p>You can then LEFT OUTER JOIN this to your main query to ensure the gaps are populated:</p> <pre><code>with the_dates as ( select to_date('01-01-2012','DD-MM-YYYY') + level - 1 as the_date from dual connect by level &lt;= to_date('01-01-2012','DD-MM-YYYY') - to_date('31-12-2012','DD-MM-YYYY') + 1 ) select sum(b.cnt), trunc(a.the_date, 'MM') from the_dates a left outer join data b on a.the_date = b.date group by trunc(a.the_date, 'MM') order by trunc(a.the_date, 'MM') </code></pre> <p>You no longer need the WHERE clause as this is taken care of in the JOIN. Note that I'm not using the DATE column from your main table but the date from the generated one instead. This will work if you want to modify the dates to not be the end of the month but if you want it month-wise you could truncate the date in the WITH clause. You should be aware of indexes before doing this though. If your table is indexed on DATE and not <code>TRUNC(DATE, 'MM')</code> then it is preferable to JOIN on DATE alone.</p> <p>DATE is a bad name for a column as it's a reserved word; I suspect you're not using it but you should be aware.</p> <p>If you were using a calender table it would look something like this:</p> <pre><code>select sum(b.cnt), trunc(a.the_date, 'MM') from calender_table a left outer join data b on a.the_date = b.date where a.the_date &gt;= to_date('01-01-2012','DD-MM-YYYY') and a.the_date &lt;= to_date('31-12-2012','DD-MM-YYYY') group by trunc(a.the_date, 'MM') order by trunc(a.the_date, 'MM') </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload