Avoid a divide by error to zero using offset

Version: 11g

Hello

Yesterday was a great help by Frank et Al concerning a request for the increase of the % of the previous year

SQL to get % increase in the amount of the previous year

One problem that I'm faced with this is that if the specific 'exp_type' does not exist in the table for a given year, I get the "division by zero error.

It works fine when there are values for all years. Is there a way to get around this? Maybe the value null or 0 but not raise an error. I tried to use NVL but did not work

{code}


WITH total AS
(

TO_CHAR (date_exp, 'YYYY') SELECT an
SUM(CASE WHEN exp_type =:P1_YOY_PERCENT_LIST THEN exp_amt ELSE 0 END) AS Type
Of exp_main
TO_CHAR GROUP (date_exp, 'YYYY')

)
SELECT year 'year '.
Type
TO_CHAR ((Type/Type of NVL (LAG (Type) (any ORDER PER year)), * 100)-100, '999990') | ' %' "% increase.
OF THE total amount
ORDER BY year DESC

{code}


FYI - the: P1_YOY_PERCENT_LIST is just a value in the Apex that I use to allow users to select any 'exp_type' for who they want to see the increase in % of the previous year.

Thank you
Ryan

Published by: ryansun on November 29, 2012 12:37 AM

Published by: ryansun on November 29, 2012 01:02

Hi, Ryan.

ryansun wrote:
Version: 11g

Hello

Yesterday was a great help by Frank et Al concerning a request for the increase of the % of the previous year

SQL to get % increase in the amount of the previous year

One problem that I'm faced with this is that if the specific 'exp_type' does not exist in the table for a given year, I get the "division by zero error.

It works fine when there are values for all years. Is there a way to get around this? Maybe the value null or 0 but not raise an error. I tried to use NVL but did not work

{code}

WITH total AS
(

TO_CHAR (date_exp, 'YYYY') SELECT an
SUM(CASE WHEN exp_type =:P1_YOY_PERCENT_LIST THEN exp_amt ELSE 0 END) AS Type
{code}

You are actually providing the 0 value in the ELSE clause. If you leave just off of the ELSE clause, then SUM returns NULL when there is no line with the given exp_type.
{code}
Sum(case when exp_type =:P1_YOY_PERCENT_LIST Then exp_amt end) AS Type
{code}
There is always a problem if exp_amt can really be 0 or exp_amt can be a combination of positive and negative numbers which could total 0.

{code}
Of exp_main
TO_CHAR GROUP (date_exp, 'YYYY')

)
SELECT year 'year '.
Type
TO_CHAR ((Type/Type of NVL (LAG (Type) (any ORDER PER year)), * 100)-100, '999990') | ' %' "% increase.
OF THE total amount
ORDER BY year DESC

{code}

FYI - the: P1_YOY_PERCENT_LIST is just a value in the Apex that I use to allow users to select any 'exp_type' for who they want to see the increase in % of the previous year.

Thank you
Ryan

The standard method to avoid division by 0 in x errors / when there may be 0 is
{code}
x / NULLIF (y, 0)
{code}
This returns null if y = 0. In your case, which would result in:
{code}
To_char ((Type
/ NULLIF (NVL (LAG (Type) (ORDER BY year)
Type
)
0
) * 100
) - 100
'999990'
) || '%' "% increase.
{code}
which guarantees that you will get the NULL value instead of the division by 0 error, but that means that the whole expression will be "%" when the number is NULL. If you really want the % sign in the set of results and not just the head, then use CASE, as Boneist suggested and cumulative Sven.

Tags: Database

Similar Questions

  • Using bulk collect into with assistance from the limit to avoid the TEMP tablespace error run out?

    Hi all

    I want to know if using bulk collect into limit will help to avoid the TEMP tablespace error run out.

    We use Oracle 11 g R1.

    I am assigned to a task of creating journal facilitated for all tables in a query of the APEX.

    I create procedures to execute some sql statements to create a DEC (Create table select), and then fires on these tables.

    We have about three tables with more than 26 million records.

    It seems very well running until we reached a table with more than 15 million record, we got an error says that Miss tablespace TEMP.

    I googled on this topic and retrieve the tips:

    Use NO LOG

    Parallel use

    BULK COLLECT INTO limited

    However, the questions for those above usually short-term memory rather than running out of TEMPORARY tablespace.

    I'm just a junior developer and does not have dealed with table more than 10 million documents at a time like this before.

    The database support is outsourced. If we try to keep it as minimal contact with the DBA as possible. My Manager asked me to find a solution without asking the administrator to extend the TEMP tablespace.

    I wrote a few BULK COLLECT INTO to insert about 300,000 like once on the development environment. It seems.

    But the code works only against a 000 4000 table of records. I am trying to add more data into the Test table, but yet again, we lack the tablespace on DEV (this time, it's a step a TEMP data)

    I'll give it a go against the table of 26 million records on the Production of this weekend. I just want to know if it is worth trying.

    Thanks for reading this.

    Ann

    I really need check that you did not have the sizes of huge line (like several K by rank), they are not too bad at all, which is good!

    A good rule of thumb to maximize the amount of limit clause, is to see how much memory you can afford to consume in the PGA (to avoid the number of calls to the extraction and forall section and therefore the context switches) and adjust the limit to be as close to that amount as possible.

    Use the routines below to check at what threshold value would be better suited for your system because it depends on your memory allocation and CPU consumption.  Flexibility, based on your limits of PGA, as lines of length vary, but this method will get a good order of magnitude.

    CREATE OR REPLACE PROCEDURE show_pga_memory (context_in IN VARCHAR2 DEFAULT NULL)

    IS

    l_memory NUMBER;

    BEGIN

    SELECT st. VALUE

    IN l_memory

    SYS.v_$ session se, SYS.v_$ sesstat st, SYS.v_$ statname nm

    WHERE se.audsid = USERENV ('SESSIONID')

    AND st.statistic # nm.statistic = #.

    AND themselves. SID = st. SID

    AND nm.NAME = 'pga session in memory. "

    Dbms_output.put_line (CASE

    WHEN context_in IS NULL

    THEN NULL

    ELSE context_in | ' - '

    END

    || 'Used in the session PGA memory ='

    || To_char (l_memory)

    );

    END show_pga_memory;

    DECLARE

    PROCEDURE fetch_all_rows (limit_in IN PLS_INTEGER)

    IS

    CURSOR source_cur

    IS

    SELECT *.

    FROM YOUR_TABLE;

    TYPE source_aat IS TABLE OF source_cur % ROWTYPE

    INDEX BY PLS_INTEGER;

    l_source source_aat;

    l_start PLS_INTEGER;

    l_end PLS_INTEGER;

    BEGIN

    DBMS_SESSION.free_unused_user_memory;

    show_pga_memory (limit_in |) "- BEFORE"); "."

    l_start: = DBMS_UTILITY.get_cpu_time;

    OPEN source_cur.

    LOOP

    EXTRACTION source_cur

    LOOSE COLLECTION l_source LIMITED limit_in;

    WHEN l_source EXIT. COUNT = 0;

    END LOOP;

    CLOSE Source_cur;

    l_end: = DBMS_UTILITY.get_cpu_time;

    Dbms_output.put_line (' elapsed time CPU for limit of ')

    || limit_in

    || ' = '

    || To_char (l_end - l_start)

    );

    show_pga_memory (limit_in |) "- AFTER");

    END fetch_all_rows;

    BEGIN

    fetch_all_rows (20000);

    fetch_all_rows (40000);

    fetch_all_rows (60000);

    fetch_all_rows (80000);

    fetch_all_rows (100000);

    fetch_all_rows (150000);

    fetch_all_rows (250000);

    -etc.

    END;

  • In numbers, I can't use then "/" operator to divide 2 cell, when I use may 7 does not appear "/", appear.

    In numbers, I can't use then ' / ' operator to divide 2 cell, when I use Shft + 7 does not appear "/", appear ' + '.

    Apple saw fit to replace the ' / ' with the Obelus ("÷") that often resembles a plus.  Look very carefully and you will see the point above and below the line.

    Also if you look at the result, 6/3 is 2 step 8 if the operator acted as the addition operator

  • Compaq Presario CQ71 - error 1002 when using recovery (windows Vista)

    Hi guys,.

    I just encountered error 1002 while using the recovery... Recovery successfully crossed reformattng my drive, but crashed before reinstaling the original content. It's okay if I'm trying to hard drive or dvd rom recovery, all this translates into error 1002. I did some research and it seems that it is a very common error in hp without adequate solution products. I think I'm out of luck because my warranty expired years ago... How can I solve this problem? For me, it seems that recovery content originally placed on my hard drive (and later burned on the DVD by me) had been damaged. I see 2 possible solutions here:

    -to order an another recovery of the drives together (although I saw a few reviews it did not)

    -buy the new "Windows" and install a new fresh install (I will be able to perform the new installation at all?)

    I'd really appreciate pointers as I really don't want to lose my money for a solution that would work!

    Kind regards

    Robert

    Hello

    You can call the MSFT customer service and they will generally be able to find it for you.

    http://answerdesk.microsoftstore.com/msusa/en-us/answerdesk/answertech

  • Windows 7 error 14001 while using iTunes on my windows XP, please help

    Windows 7 error 14001 while using iTunes on my windows XP, please help

    Please ask your question on the forum from iTunes here: https://discussions.apple.com/community/itunes/itunes_for_windows?view=discussions

  • In Vista, doing the system restore, get error "unspecified error occurred when using System Restore.

    My system restore keeps coming back with the error, unspecified error occurred when using System Restore. Cannot change files. Also, after that I am unable to use my avast antivirus. All the sheilds on my Avast are lost. I; m not computer saavy so please help me

    Hello

    You can be infected with the Malware

    malware stops normally you use the system restore protect themselves remove you

    Download update and scan with the free version of malwarebytes anti-malware

    http://www.Malwarebytes.org/MBAM.php

    You can also download and run rkill to stop the process of problem before you download and scan with malwarebytes

    http://www.bleepingcomputer.com/download/anti-virus/rkill

    If it does not remove the problem and or work correctly in normal mode do work above in safe mode with networking

    Windows Vista

    Using the F8 method:

    1. Restart your computer.
    2. When the computer starts, you will see your computer hardware are listed. When you see this information begins to tap theF8 key repeatedly until you are presented with theBoot Options Advanced Windows Vista.
    3. Select the Safe Mode with networking with the arrow keys.
    4. Then press enter on your keyboard to start mode without failure of Vista.
    5. To start Windows, you'll be a typical logon screen. Connect to your computer and Vista goes into safe mode.
    6. Do whatever tasks you need and when you are done, reboot to return to normal mode.

    If not, try Safe Mode do a system restore

    http://www.windowsvistauserguide.com/system_restore.htm

    Windows Vista

    Using the F8 method:

    1. Restart your computer.
    2. When the computer starts, you will see your computer hardware are listed. When you see this information begins to tap theF8 key repeatedly until you are presented with theBoot Options Advanced Windows Vista.
    3. Select the Safe Mode option with the arrow keys.
    4. Then press enter on your keyboard to start mode without failure of Vista.
    5. To start Windows, you'll be a typical logon screen. Connect to your computer and Vista goes into safe mode.
    6. Do whatever tasks you need and when you are done, reboot to return to normal mode.
  • Blue screen error: 0x0000001a when using system to restore with new hard drive disk

    original title: blue screen error when you use the system disk to restore with new hard drive

    I bought a new hard drive to my computer because the old one gave me a bunch of error messages on screen blues. I installed in the tower and tried to use my restore and system recovery disks that the manufacturer has given me, the process has got to the last disk then asked for the system once again restore disc, and then began to load the last steps and went to blue screen error. I don't know what to do, I mean it's a whole new drive hard, so where could the error come, theres nothing on the hard drive because I have not yet used really, yet. Help, please

    I have finally fixed the problem myself. The problem was that one of the sticks three memory was bad and the only way I could test this error. I took two sticks a left, used disks I had and was able to restore my computer, then I put a stick, turned on the computer, had no errors so I let him, so I put the last stick in and com immediately on, I had the Disconnections: memory management and that's when I knew that the last stick of memory was bad I took it back and now my computer works well and I can't buy more memory for not too. So if someone gets this BOSD error on memory, I'd say 8/10 computers have bad memory (not a number). If youcannot run the tool of diagnosis of memory like me then I would suggest to do what I did with the trial and error, it was the only way to understand the problem. Thanks for your help

  • build error of createUser using the c# code sample

    I get the following build error when you use the c# code for the createUser use method example.

    I use VisualStudio2008 and the Blackberry_Admin_API - 5.0 - US.pdf c# code example.

    Build error States:

    Cannot implicitly convert type 'BESAdmin.BASemailExchangeWebService.EnableBlackBerryUserAttributesType' in 'BESAdmin.BASCoreWebService.EnableBlackBerryUserAttributesType' C:\VS2008\BESAdmin\BESAdmin\Form1.cs 76 488 BESAdmin

    The build error is on this part of the code:

    for (int j = 0; j)< attributes.enableblackberryuserattributes.length;="">

    {

    userEnableBBAttributes.enableBlackBerryUserAttributes [j] = attributes.enableBlackBerryUserAttributes [j];

    }

    Everyone has this same problem and found the solution?  It seems that there is something missing or incorrect in the sample code around type conversion between the EnableBlackberryAttributesType.

    Thank you, Ed

    Hi Ed,

    I tried throwing the code example in a project already created the mine and has not known this error at compile. The two types of objects must be the same, so I don't know why there is no conflict with assignment.

    Please try to use the sample code to create a user from the BAA API reference documents:

    http://www.BlackBerry.com/developers/docs/BAA/5.0.0/

    Or the Knowledge Base of the developer section:

    http://www.BlackBerry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/1608023/How_To_-_Get _...

    It can also be a good idea to recreate your proxy to do this.

    Let us know if the problem is still evident with the examples above.

  • Error trying to use remote desktop.

    I'm having a repeatable error trying to use remote desktop in Windows 7 Pro.

    The error I get is:

    Your computer could not connect to another session from the console on the remote computer, because you already have a current console session.

    I don't have sssion another current.  I get this error right after a fresh reboot.  A Mater of fact due to multiple problems, I got with a new computer, I have re-installed Windows on another hard drive to make sure that everything was fresh.  I get the same error.

    I am connected with administrator privileges and I got this error the first time I tried to establish a session.  It's the same problem I had with the other installation of Windows.  Can someone point me to a solution?  I'm relatively new to versions of Windows 7, but not at the earliest.

    Thanks to all who can help.

    Bill

    See what some of these word to say about the problems with the file on your computer and incorrect IP addresses of Hosts.

    Remote Desktop connection - already have a console session
    http://social.answers.Microsoft.com/forums/en-us/w7programs/thread/6bdafe59-7437-4E02-9139-c22536b8f28e

    Win 7 RC your computer could not connect to another session from the console on the remote computer because you already have a current console session
    http://social.technet.Microsoft.com/forums/en/w7itpronetworking/thread/5ce19e8c-DFFB-4BCB-A176-87534993eaa1

    http://www.google.com.au/search?hl=en&rls=com.microsoft%3Aen-au%3AIE-Address&q=%22Computer+could+not+connect+to+another+console+session+on+the+remote+computer%22+because+you+already+have+a+console+session+in+progress&btnG=Search&aq=f&aqi=&aql=&oq=&gs_rfai=

    You domestic Remote Desktop connection slots between and within your own network, or is it a work at home type of connection?

  • When I tried the update of lightroom cc2015 I get a U44M2P7 error message. I tried to rename the file update and a new attempt and also update manually but still the same error. I use a mac with os x El Capitan version 10.11.3 any suggestions would be gra

    When I tried the lightroom cc2015 update I get an update of the failure U44M2P7 error message. I tried to rename the file update and a new attempt and also update manually but still the same error. I use a mac with os x El Capitan version 10.11.3 any suggestions would be greatly appreciated.

    U44... Update error http://forums.adobe.com/thread/1289956 can help

  • When you try to attach a PDF file as an object the WORD 2013 64 bit I'm estates following error: "the program used to create this object is AcroExch. This program is either not installed on your computer, or it does not. To change this, install AcroE

    When you try to attach a PDF file as an object the WORD 2013 64 bit I'm estates following error: "the program used to create this object is AcroExch. This program is either not installed on your computer, or it does not. To change this, install AcroExch or ensure that all the dialog boxes in AcroExch are closed. "even disabled protection at startup mode. Who made no difference

    Hi sdesk.

    This problem occurs with the 64-bit application as Acrobat is a 32-bit application making it incompatible to insert objects into a MS Word 64-bit application.

    As a workaround solution insert the object as a 'Create New' rather than create a file.

    Let me know if it helps.

    Kind regards
    Nicos

  • Error 16 while using the applications in the suite Adobe CC 2015...

    Error 16 while using all the apps in the Adobe CC 2015 suite, it is installed via drive Application Jukebox, I have administrator rights on my laptop and have tried the solutions of permissions on the Adobe support site.

    Completely blocked as to why he suddenly not working.

    1A tried to change permissions on folders of PCD SLstore as intructed.

    2 tried to run with administrator rights.

    3. I tried uninstalling and reinstalling.

    Other help would be great, thanks.

    Error 16 corresponds to the file permission issue and the steps mentioned in the link I provided are useful in some cases.

    In this case, we should try to assign permissions to all of the Adobe directory. Please follow the steps as mentioned below according to your operating system.

    Mac

    1) navigate to the following locations and assign all permissions to the adobe folders to the current user. To navigate, open finder and click on going in the bar on then click goto... type/library/application support of / and then click OK.

    (2) to assign the authorization right click on adobe folder and click on Get info... A window will open. Then click on the lock symbol to allow editing. Then click on sign + to add your user name. Then change read only to read and write. Then click gear icon on the bottom and click on apply to the elements included and click ok...

    Windows

    1) navigate to the following locations and assign all permissions to the adobe folders to the current user.  (Right click on adobe folder select properties then click on the Security tab, click on edit and select current user, that you are connected to, select full control, click on apply and then ok)

    C: / / program data (to view hidden files to see this folder)

    C: / / program files 86 x files / common

    C: / / program files x 86.

    C: / / program files common files

    C: //program files.

    (2) try to run the adobe application

    change to the authorisation should look like image below

  • I just installed lightroom cc on a brand new and reveived laptop 2 following errors.  can someone tell me what they mean and wll prevent of sing lightroom?  ERROR: third charge useful Installer vcredist_x64.exe failed with exit code:-2147024546

    I just installed lightroom cc on a laptop computer brand new and reveived errors the following 2.  can someone tell me what they mean and they will prevent to use lightroom?

    ERROR: third charge useful Installer vcredist_x64.exe failed with exit code:-2147024546

    AND

    ERROR: Cannot install the Microsoft Visual C++ 2012 Redistributable Package (x 64). Please try to install by double-clicking the executable file to "C:\Users\CHRIST~1\AppData\Local\Temp\{7A86BA4B-C59E-4130-9C4D-DA8765643E21}\Lightroom_6_ LS11\payloads\Microsoft VC 2012 Redist (x 64) \vcredist_x64.exe", or download and install the 2012 Microsoft Visual C++ Redistributable Package last (x 64) Microsoft Web site - www.microsoft.com

    Download Visual C++ Redistributable for Visual Studio 2012 updated 4 of the official Microsoft Download Center

  • Error when you use the Group feature

    Oracle forms6i

    Hai

    While I compile my coding it will compile correctly, but when I tried to run I revealed an error in the function of group

    my code is


    If (NTC <>0) then
    Select the BAR code, RESPONDENT, OUTTIME today_bar, today_in, today_out from dail_att where BARCODE =: bar code
    and ATTEND_DATE =: bardate;
    Update dail_att set outtime = max(:bartime) where barcode =: bar code
    and ATTEND_DATE =: bardate;

    on the other
    If (cnt2 <>0) then

    Select RESPONDENT, OUTTIME in yest_in, yest_out from dail_att where BARCODE =: bar code
    and ATTEND_DATE =: bardate-1;

    If (yest_in is not null and yest_out is null) then
    Update dail_att set outtime = max(:bartime) where barcode =: bar code
    and ATTEND_DATE =: bardate-1;

    on the other
    insert into dail_att(barcode,intime,attend_date)
    values (: Barcode, min(:Bartime),: bardate);
    end if;
    on the other
    If: bartime between 0100 and 0630
    insert into dail_att(barcode,intime,attend_date)
    values (: Barcode, min(:Bartime),: bardate-1);

    Update dail_att set outtime = max(:bartime) where barcode =: bar code
    and ATTEND_DATE =: bardate-1;

    on the other

    insert into dail_att(barcode,intime,attend_date)
    values (: Barcode,: min (Bartime),: bardate);
    end if;
    end if;
    end if;

    while I'm trying this groupfunction it throws error while I use seen tell me how to use the Group feature and where
    to use

    Regadrs

    Srikkanth.M

    Srikkanth,

    For this you need to calculate the max outside of the update statement and then use this value in the update statement.

    The bartime is a control in the block?

    If Yes, then you need to find the max manually, and if it isn't, then you can write a sub query to find the maximum value.

    Kind regards

    Manu.

    If my response or response from another person was helpful, please mark accordingly

  • Error: C00D11EF while using Windows Media Player to synchronize the iPod

    Original title: Installed a new drive, iPod syncs not; using MGTEK for conversion.

    Remember - this is a public forum so never post private information such as numbers of mail or telephone!

    Ideas:

    • You have problems with programs
    • Error messages
    • Recent changes to your computer
    • What you have already tried to solve the problem

    MGTEK is a convenient way to sync iPod/touch etc by using WMP. Its a plug-in. She avoids you having to use iTunes...!

    Just UN-installing it, re-boot, then re - install it should work. Otherwise, you will need to manually reset/clear your library in WMP.

    You can safetly remove temporary files.

    See you soon,.

    Jery

Maybe you are looking for

  • Foxfire flies from site to site, but the links open very slowly in my e-mail program. Why the difference?

    Foxfire when open, flies from site to site, but when I click on a link in my email, even if Foxfire is open, it is very very slow to react, aggravatingly Yes. Why the difference?

  • How to open my HP Touchsmart 320-1050 to check the fan

    My Touchsmart 320-1050 is 18 months old and there is two weeks the fan started to have really strong.  Looks like the engine of a plane is racing upwards for takeoff. How can I open the back to see if the fan is dusty or has to be replaced.  We live

  • the two shift keys not working not

    I got an error of streamci.dll earlier today.  to restart, I discovered that my two shift keys were working is no longer.  given that I made experiences... Here's what I tried... 1. I tried to restart 2 i tried to uninstall and reinstall the keyboard

  • How to find the product key of Windows 7 or Windows 10

    I have a laptop of lenovo B590 which was preinstalled windows 7 ultimate. I upgraded to windows 10 as requested by microsoft. and it works well. but I don't have the product key for windows. so, if I get any problems in the future and I need to reins

  • Unable to access Windows 7

    We cannot access Windows on one of the 2 user accounts on my other computer (office) - both say that the relevant password is incorrect. It runs Windows 7 Home Premium, for remote access is not possible. The problem started at startup and coincided w