Show data from table even if there is no data!! Oracle

后端 未结 3 1736
悲&欢浪女
悲&欢浪女 2021-01-25 05:34

I have a query which shows count of messages received based on dates. For Eg:

1 | 1-May-2012 
3 | 3-May-2012 
4 | 6-May-2012 
7 | 7-May-2012 
9 | 9-May-2012 
5 |         


        
3条回答
  •  遥遥无期
    2021-01-25 06:03

    First, it sounds like your application would benefit from a calendar table. A calendar table is a list of dates and information about the dates.

    Second, you can do this without using temporary tables. Here is the approach:

    with constants as (select min(thedate>) as firstdate from )
         dates as (select(  + rownum - 1) as thedate
                   from (select rownum
                         from 
    cross join constants where rownum < sysdate - + 1 ) seq ) select dates.thedate, count(t.date) from dates left outer join
    t on t.date = dates.thedate group by dates.thedate

    Here is the idea. The alias constants records the earliest date in your table. The alias dates then creates a sequence of dates. The inner subquery calculates a sequence of integers, using rownum, and then adds these to the first date. Note this assumes that you have on average at least one transaction per date. If not, you can use a bigger table.

    The final part is the join that is used to bring back information about the dates. Note the use of count(t.date) instead of count(*). This counts the number of records in your table, which should be 0 for dates with no data.

    提交回复
    热议问题