Cumulative total for each day - how to deal with nulls

I'm on 11.2.0.3.  I want to write a query to calculate a running total of the incidents a day - this request will be used for an APEX line chart.


Sample table and data:

create table sales (
  id number primary key,
  time_of_sale date,
  item varchar2(20));


insert into sales values (1, to_date('02-JAN-2013','DD-MON-YYYY'), 'book');
insert into sales values (2, to_date('03-JAN-2013','DD-MON-YYYY'), 'candle');
insert into sales values (3, to_date('05-JAN-2013','DD-MON-YYYY'), 'bicycle');
insert into sales values (4, to_date('05-JAN-2013','DD-MON-YYYY'), 'football');
insert into sales values (5, to_date('07-JAN-2013','DD-MON-YYYY'), 'football');
insert into sales values (6, to_date('10-JAN-2013','DD-MON-YYYY'), 'elephant');
insert into sales values (7, to_date('10-JAN-2013','DD-MON-YYYY'), 'turtle');
insert into sales values (8, to_date('10-JAN-2013','DD-MON-YYYY'), 'book');
insert into sales values (9, to_date('10-JAN-2013','DD-MON-YYYY'), 'candle');
insert into sales values (10, to_date('10-JAN-2013','DD-MON-YYYY'), 'bicycle');
commit;

For each of the days between 1 January and 10 Jan I want to get the total functioning of the number of sales.

So the output l would like is:

DAY ITEMS_PER_DAY

--------- -------------

1ST JANUARY 13 0

JANUARY 2, 13 1

JANUARY 3, 13 2

JANUARY 4, 13 2

5 JANUARY 13 4

JANUARY 6, 13 4

JANUARY 7, 13 5

JANUARY 8, 13 5

JANUARY 9, 13 5

10 JANUARY 13 10

So even if there is no sale on January 4, we show the total of the previous day.

If I can create a series of dates using the:

select trunc((to_date('01-JAN-2013','DD-MON-YYYY')-1) + rownum) day 
from dual 
connect by rownum <= 10

And I can't the cumulative aid total:

select trunc(time_of_sale) as day, sum(count(*)) over (order by trunc(time_of_sale)) as items_per_day
from sales
group by trunc(time_of_sale)

Overall, it gives me:

SQL > select

2 a.day as the day,

3 b.items_per_day

4 of

5 (select trunc((to_date('01-JAN-2013','DD-MON-YYYY')-1) + rownum) as day

6 double

7 plug by rownum < = 10).

8 (select trunc (time_of_sale) day, sum (count (*)) (trunc (time_of_sale) order) as items_per_day

9 sales

10 group by trunc (time_of_sale)) b

11 where a.day = b.day [+] - replace by parentheses to avoid the formatting of the forum

12 order by a.day

13.

DAY ITEMS_PER_DAY

--------- -------------

1st January 13 null

JANUARY 2, 13 1

JANUARY 3, 13 2

Value null 4 January 13

5 JANUARY 13 4

Value null January 6, 13

JANUARY 7, 13 5

Value null January 8, 13

Value null January 9, 13

10 JANUARY 13 10

It's not exactly what I'm looking for.  I played a bit with a lag, but had no success.

Any ideas?

Thank you

John

Hi, John,.

You want to do the SUM after the outer join, like this:

WITH days_wanted AS

(

SELECT TO_DATE (January 1, 2013 ', 'DD-MON-YYYY') + ROWNUM - 1 day YOU

OF the double

CONNECT BY ROWNUM<=>

)

SELECT d.day

SUM (COUNT (s.id)) OVER (ORDER BY d.day) AS items_to_date

OF days_wanted d

S sale LEFT OUTER JOIN ON TRUNC (s.time_of_sale) = d.day

GROUP BY d.day

ORDER BY d.day

;

Note that we must use COUNT (s.id) instead of COUNT (*) here, because, given that it is evaluated once the outer join, COUNT (*) would be taken into account less than $ 1 a day, because the outer join ensures there will be at least 1 row in the game for each row in days_wanted, whether or not it matches anything in sales.

It wouldn't work using the old join syntax, too, but I suggest to use the ANSI syntax, especially for outer joins.  It reduces the amount and the complexity of the coding, and which allows to reduce the number of errors.  (Also, it avoids the problem of the display of this site.)

Tags: Database

Similar Questions

  • In a Windows Vista-based computer, a message appears that the password to expire in 14 days, how to deal with this?

    My current research indicates that this should be a problem in Windows XP, I can't find anything that relates to Windos Vista on it.  Can anyone help?

    GD,

    Maybe this can help you:

    http://answers.Microsoft.com/en-us/Windows/Forum/Windows_7-security/how-to-disable-password-expiration-reminder/8a944967-2b18-4B8A-9d32-2e6580ff1bbc

    (parameters of expiration of password in Vista is the same as WIN7)

    LC

  • How to deal with NULL values in regexp_substr?

    DECLARE
       TYPE t_rec IS TABLE OF VARCHAR2(200);
    
    /* case 1 */
       l_input    varchar2(100) := '28/09/2009 00:00:00|AFRISB|FC|773|7|17|512|76|60|U|';
    /* case 2 */
    --   l_input    VARCHAR2(100) := '06/10/2009 00:00:00|PDIERR|PS|999|0|1|0|0||U|';
       l_bars     PLS_INTEGER;
       l_fields   PLS_INTEGER;
       l_rec      t_rec := t_rec();
    BEGIN
       l_bars     := regexp_count(l_input, '\|', 1, 'i');
       l_fields   := l_bars + 1;
    
       FOR fld IN 1 .. l_fields
       LOOP
          l_rec.EXTEND();
    
          l_rec(fld)   := REGEXP_SUBSTR(l_input, '[^|]+', 1, fld);
          dbms_output.put_line('Fld ' || fld || ': ' || l_rec(fld));
       END LOOP;
    END;
    

    The above code is that I break a string of pipe delimited into individual elements.

    Looking at the case 1 in the code, the output displays each field correctly. However in case 2, the 9th field is null (nothing between the two tubes) so the regexp_substr 19 online is assigning the 'U' in the box 10 as a field 9.

    What should I do to get the line 19 to correctly assign a NULL value to field 9?

    Information about the version of the database are:

    BANNER

    --------------------------------------------------------------------------------

    12 c Oracle database Release 12.1.0.1.0 - 64 bit Production
    PL/SQL Release 12.1.0.1.0 - Production
    CORE Production 12.1.0.1.0
    AMT for 64-bit Windows: Version 12.1.0.1.0 - Production

    NLSRTL Version 12.1.0.1.0 - Production

    Thank you

    Steve

    Hello

    If you want to use regexes, so instead of

    REGEXP_SUBSTR (l_input, "[^ |]") +', 1, fld);

    use

    REGEXP_SUBSTR (l_input

    , '([^|] *)(\|| $)'

    -P

    fld

    NULL

    -P

    );

    . The 6th argument to REGEXP_SUBSTR is a new feature of Oracle 11.1.  It's kind of a back reference. Normally, REGEXP_SUBSTR returns the substring that matches the pattern in the 2nd argument.  If the 6th argument is 1, however, REGEXP_SUBSTR returns only the part of the pattern between the 1st on the left '(' et sa correspondance)."

  • Calendar of the apex; limit values for each day/cell

    Apex 4.2

    I'm working on a calendar widget to my page. The calendar will be specific sectors (using the abbreviation of sector space maximze) for each day. When you use the calendar, I noticed the sectors more you have, the cell for this day will begin to stretch down / vertically. I tried to change this so that a specific day / cell would show only a number of areas. For example, maybe one day 20 sectors are attributed to him, however, I only want to show 5 of them and then a text saying 'See more'. The text 'see more' will eventually be a link, but it's far from being the problem.

    Initially, the request for this was along the lines of:

    select
    the_id, the_date, the_sector, the sector_abbrev
    from Table
    where this = that
    

    It would show all sectors for all the days on the calendar. Yet once, I wanted to limit the output every day as some days would indicate all 20 sectors (their abbreviations), and some would be 3 or four in function. So to say that there are 30 sectors (10 1st), 4 of the 15, 12 on 20-4 on November 29. I want to allow only five abbreviations of sector which must appear in a cell until the link "see more" appears. I came up with the following query:

    Select
    the_sector_abbrev, the_id, the_date, the sector
    from Table
    where rownum <= 5 and (this = that)
    union all
    Select 'View More', null, null, null
    from dual
    

    I found that it would be limiting my calendar for showing that four areas throughout the month of November and not for each day / cell on the calendar. I am to discover that 'rownum' is perhaps not the way to go. I don't know how to specify for each of the calendar days rownum. I don't know how to capture every day / the Calendar cell. Maybe I need a more complicated or a subquery where clause. But overall, from my example above, the 1st show four of the sectors and then the link "See more", the 15th would show the four sectors and thats all, the 20th century would show four sectors and her "see more" link and so on.

    Any help on this would be greatly appreciated. Thanks in advance.

    NewApexCoder wrote:

    I had no idea of the possible application of solution would be too complex.

    It is not the case:

    with calendar_data as (
        select
            ins.sector_abbrev_name
          , sch.hwe_inspection_scheduling_id
          , sch.inspection_date
          , sch.instructions
          , sch.inspection_sector_id
          , sch.high_water_event_id
          , ins.inspection_sector_name
          , hwe.event_name
          , row_number()
                over (
                  partition by sch.inspection_date
                  order by sch.inspection_date, ins.inspection_sector_name) day_sector_rn
        from
            hwe_inspection_scheduling sch
              left join inspection_sectors ins
                on sch.inspection_sector_id = ins.inspection_sector_id
              left join high_water_events hwe
                on sch.high_water_event_id = hwe.high_water_event_id
        where
            (   sch.high_water_event_id = :p0_high_water_event_id
             or :p0_high_water_event_id is null))
    select
        inspection_sector_id
      , inspection_date
      , inspection_sector_name
      , sector_abbrev_name
      , ...
      , null -- Generate URL for sector links here
    from
        calendar_data
    where
        day_sector_rn <= 5
    union all
    select
        null
      , trunc(the_date) + 1 - interval '1' second
      , null
      , 'View More…'
      , ...
      , null -- Generate URL for "View More..." links here
    from
        calendar_data
    group by
        the_date
    having
        count(*) > 5
    
  • Select the last value for each day of the table

    Hello!

    I have a table that contains several measures for each day. I need two queries on this table, and I'm not sure how to write them.

    The table stores the rows (sample data)
    *DateCol1                 Value       Database*
    27.09.2009 12:00:00       100           DB1
    27.09.2009 20:00:00       150           DB1
    27.09.2009 12:00:00       1000          DB2
    27.09.2009 20:00:00       1100          DB2
    28.09.2009 12:00:00       200           DB1
    28.09.2009 20:00:00       220           DB1
    28.09.2009 12:00:00       1500          DB2
    28.09.2009 20:00:00       2000          DB2
    Explanation of the data in the sample table:
    We measure the size of the data files belonging to each database to one or more times a day. The value column indicates the size of the files of database for each database at some point (date in DateCol1 European model).


    What I need:
    Query 1:
    The query must return to the last action for each day and the database. Like this:
    *DateCol1       Value      Database*
    27.09.2009        150          DB1
    27.09.2009       1100          DB2
    28.09.2009        220          DB1
    28.09.2009       2000          DB2
    Query 2:
    The query should return the average measurement for each day and the database. Like this:
    *DateCol1       Value      Database*
    27.09.2009       125          DB1
    27.09.2009      1050          DB2
    28.09.2009       210          DB1
    28.09.2009      1750          DB2
    Could someone please help me to write these two queries?

    Please let me know if you need further information.

    Published by: user7066552 on September 29, 2009 10:17

    Published by: user7066552 on September 29, 2009 10:17

    Why two queries when it suffice ;)

    SQL> select dt
      2       , db
      3       , val
      4       , avg_val
      5    from (
      6  select dt
      7       , val
      8       , db
      9       , row_number () over (partition by db, trunc (dt)
     10                                 order by dt desc
     11                            ) rn
     12       , avg (val) over (partition by db, trunc (dt)) avg_val
     13    from test)
     14   where rn = 1
     15  order by dt
     16  /
    
    DT        DB           VAL    AVG_VAL
    --------- ----- ---------- ----------
    27-SEP-09 DB2         1100       1050
    27-SEP-09 DB1          150        125
    28-SEP-09 DB2         2000       1750
    28-SEP-09 DB1          220        210
    
  • Delete based on specific hours for each day

    Hello

    I have a table with a field of date DD-MM-YYYY HH:MIN:SS
    Table contains date since 2006 and I just need to keep the entries with date DD-MM-YYYY 00:00 (midnight only registers for each day)

    Thanks in advance for any help.

    drbiloukos wrote:

    ...
    ...
    ...
    14-JAN-13
    14-JAN-13 12:01:00
    14-JAN-13 12:01:05
    14-JAN-13 12:02:03
    14-JAN-13 12:01:55
    14-JAN-13 12:02:13
    15-JAN-13
    15-JAN-13 12:01:00
    15-JAN-13 12:01:05
    15-JAN-13 12:02:03
    15-JAN-13 12:01:55
    15-JAN-13 12:02:13
    ...
    ...
    ...
    

    just need to keep accounts with

    ...
    14 JANUARY 13
    15 JANUARY 13

    LUN-JJ-AA 00:00

    that

    delete from table where date_col != trunc(date_col);
    or to keep the data
    update table set date_col = trunc(date_col)
    

    or you can add the new column

    alter table table_name add (new_date date);
    

    and update

    update table table_name set new_date = TO_DATE(TO_CHAR(old_date,'DD.MM.YYYY HH24:MI')||':00', 'DD.MM.YYYY HH24:MI' )
    

    Published by: Bawer on 16.01.2013 12:03

  • I need a query that selects the amount of records for each day of a table.

    I need a query that selects the amount of records for each day of a table.
    For example, the result would be:

    1 14 date
    Date 2-3

    etc.

    Any ideas?

    Sort:

    SELECT count ([IDCommentaire]), convert (varchar, dateAdded, 112)

    OF COMMENTSgroup by convert (varchar, dateAdded, 112)

  • How to deal with operating system windows 8.1 and apps on usb device

    Hi, I have a laptop Lenovo G505. Windows 8 64-bit was preinstalled in it. Later, I upgraded to 8.1. Laptop is almost 9 months and still under warranty. Since a few days, built Lenovo solution Center alert this analysis of hardware detected failures in one or more devices. On suggestion of Lenovo, I ran hdtune pro app in my machine and it also detected 3 hard drive errors. As my machine is under warranty, Lenovo is ready to replace my hard drive with a new one. But they say that it is the responsibility of the customer to return the windows 8.1 operating system and install in the new drive and their liability is limited to the replacement of the hard disk only. I am not computer savvy and I request concerned to guide me how to deal with operating system windows 8.1 on external media like USB, DVD, and install in the new drive. I also installed a number of apps and paid games. Therefore, I would like to resume these games also files so that I need not buy again. Assistance in this regard is required.

    Hello Mohan,

    Thanks for posting your query in Microsoft Community Forum.

    I can of course understand the situation and will be happy to help with your query.

    Let me ask you;

    • You have the key product for Windows 8 or 8.1?

    You can create an installation media (DVD/USB) for Windows 8.1 and re-install when you want. However, in order to create an installation media for Windows 8.1, you need the product key. If you don't have the product key for Windows 8.1, you can not create installation media.

    You can create the installation media for Windows 8 by using the product key Windows 8 If you have. In this case, install you Windows 8 first and then go to Windows 8.1 through store.

    As far as your paid apps (purchased by store) are concerned, you should be able to install them as soon as you sign in with the same Microsoft Account where apps were purchased.

    You can see the steps indicated by Ronnie Vernon replied on 24 December2013, re - install paid apps.

    You can follow the steps below to create installation media.

    1. Run the program Windows 8.1 configuration or installation of Windows 8 (depending on the availability of the product key for the specific operating system.
    2. When you are prompted to run or save the file, choose run

    3. When you are prompted to enter a product key, enter the 25-character product key, that you received when you purchased Windows 8.1 (or Windows 8).

    4. When you are prompted to install Windows 8.1 (or Windows 8), select install by creating media and then click Next.

    5. Select the type of media you want to use: either a Flash DRIVE or a DVD.

    To create a USB flash drive

    1. Click on the USB flash drive.

    2. Plug the USB key into a USB port on your PC.

    3. When you are prompted, select the USB key that you want to use, and then click Next.

      If you have files on the USB flash drive, it will remove them.

    To create a DVD

    1. Click on the ISO file , and then select the location where to save the ISO file.

    2. Insert a blank recordable DVD into your DVD drive.

    3. Burn the ISO of the DVD file using Windows disc Image burner, or another program DVD burning.

    Note: Ensure that the USB or DVD key that you use has nothing else stored on it and has a sufficient free space to download the Windows 8.1 Installer: about 2.3 GB for the 64-bit version.

    You can also read the article below to create a USB stick recovery.

    Create a recovery USB disk

    Hope this information is useful. Please feel free to answer in the case where you are facing in the future other problems with Windows.

    Thank you.

  • How to deal with the change in scope

    Dear,

    No org by enforcement period. Consolidation of the CDA. CDA entry.

    September, a company (X) is thrown into a perimeter (a-frame) and granted in a different consolidation perimeter (part B).

    I need perform the following acts:

    (A) CDA profit & loss of X, from September, must contribute to A scope results until December;

    (B) BAT profits/losses of X in September, October and December, must contribute to the results of scope B until December.

    (Operations under A) and B) can be automated? No idea how to do?

    I don't have a script. I need only a generic description on how you did.

    Thank you very much!

    According to my experience, assuming that you create a new entity for X under parent B, the best thing to do in these situations is to simply manage it via a journal entry.  You will write a day who would keep the CDA P & L (and in our cash flow of CDA case) result of X to the title of parent with equal and opposite impact hitting the new entity of X under B.  You post this journal in Sep, Oct, Nov and dec and continue loading data for a YEAR to X under B.

    However, if you simply drag & drop X under a new parent, I don't know how you deal with it.

    Kind regards
    Jason

  • How to deal with the table still growing?

    All tables are more and more applications. In some applications, tables become quickly more and more wide. How to deal with this problem?
    Currently I develop an application system. Should I add a large number of orders to remove the code for each table?

    The problem is delete is very time consuming.

  • How to deal with analysis PC Performance & Stability Report

    Yesterday, when I just walked into my Office Xp, an error report in a program called... uh, PC Performance & Stability Report analysis, can possibly be, telling me to correct these errors have shown under its professional service.
    How to deal with him?
    Thank you for your advice it.

    Hello MeriClaybron,

    1. have you installed any show analyzing the program on your computer?

    This problem can be caused due to infection by the Virus. I suggest that you run a virus scan on your computer using Microsoft Safety scanner and check if you have the same problem.

    http://www.Microsoft.com/security/scanner/en-us/default.aspx

  • Why it takes so long for the BlackBerry vendor to deal with accounts?

    Why it takes so long for the BlackBerry vendor to deal with accounts?

    I put in my request 3 days ago, and it has not yet been verified.

    Hello

    Could you please PM me your name of the seller? Do you get the email that asks you to send the document ID/commercial? If this isn't the case, please try to chcek your spam folder.

    Kind regards

    Satya

  • After the recent update on 06/01/2016, pdf files created on the Tamil language there are blank pages. How to deal with all this?

    After updated recent Acrobat reader, dated 06/01/2016, files already created with Tamil fonts show blank pages. How to deal with all this?

    Hi tnrk64,

    We just released Acrobat Reader for iOS version 15.4 on 23 January 2016.

    This version includes the special snag you have met.

    Would you please try it and let us know if it works for you?

    If you have problems with Acrobat Reader on the Apple App Store update, please take a look at the following page for advice: http://adobe.com/go/updatehelp

    Thank you!

  • Apparently, my memory is almost full - no idea how to deal with not having a novice such am - sd card

    Apparently, my memory is almost full - no idea how to deal with not having a novice such am - sd card

    Hi sixty.

    It can also be a good idea to begin to transfer the content from your phone to a PC/Mac to help reduce the storage room.

    It is a process usually easy, just plug the unit to a PC, on the phone screen select MTP mode when it appears.

    Once finished, you just have to access the phone's internal memory and transfer pictures/videos from the DCIM folder.

    Let us know if you need help in this kind of task.

  • I look integrated in the block of the legend of slide show, a widget like "Accordion" for, with one click, or by the way with the mouse, open a new caption for each photo. I tried with 'Accordion' Muse, it does not work. I haven't tried to copy and paste,

    Issue.

    I look integrated in the block of the legend of slide show, a widget like "Accordion" for, with one click, or by the way with the mouse, open a new caption for each photo. I tried with 'Accordion' Muse, it does not work. I haven't tried to copy and paste, but no result. The widget disappear into the legend of block. disappear. Do you have a solution?

    Thank you

    Loïc

    Accordion Panel tabs should, with click and open the container.

    Please provide the url of the site where it does not, also if you can provide an example where we can see the exact action, then it would help us.

    Thank you

    Sanjit

Maybe you are looking for

  • Remove the firefox Slider-savings

    I downloaded a utility freeware from Softonic and installed some economies-Slider. I searched the web and found one site that has a solution, but you must purchase a subscription to get the solution. Anyone know how to remove it?

  • Communication satellite U500 wifi switch control does not work

    Hello I have problem after update of the operating system from Vista 64 bit to win7 64-bit. The problem is in the wireless communication switch command before notebok. When I was with win vista, it works fine, post off - wifi off and post-wifi on (wi

  • Resize the Windows Server 2003 boot partition

    My client has Server 2003 with a RAID. The system volume / start is 12 GB. Right next to this boot on the partition volume is 30 GB of unallocated space. The rest of the disk is allocated to a separate partition in which all their data lives. Can I e

  • HP deskjet 2050 J510 series: Deskjet 2050 scan icons not opening

    I use windows 7 and until recently could open the printer and the HP support Assistant using the icons on the desktop. Now when I clicked on the icon of the printer that is used to open in Notepad, but now it wont open at all and support assistant sa

  • Error compiling WebWorks app

    I'm trying to compile an application with the SDK 2.2 Webworks and I get this error: com.yahoo.platform.yui.compressor.CssCompressor: error! : lack of battery card in: label: 18[ERROR] CAP exception has occurred What does that mean? How can I solve i