Calculation of the total quantities in SQL

Hello gurus,

I have a table that stores the quantities ordered with arrival dates and order ID this table creates a new records each time the quantity changes. So I was wondering how we could do this calculation in SQL.

Let's say I have Order ID = 218, so order Date 7/1/2103 sentence = 1100 and then for the same command id = 218 ordered = 1500 (changes).

So I want to calculate a total quantity for order number = 218

from the date = 01/07/2013 until the quantity of calcuation changes is (IE until 14/07/2013) = 14 * 1100 = 15400

and for the 15/07/2013 order quantity = 1500

TOTAL AMOUNT = 16900

The following DDL data and sample:

CREATE TABLE XX_ORD_QNTY
(
INT_ID NUMBER (15),
ORD_DATE DATE,
ORD_QNTY NUMBER (15),
ORD_ID NUMBER(15)
);


INSERT INTO  
XX_ORD_QNTY (INT_ID , ORD_QNTY , ORD_DATE , ORD_ID) VALUES ( 1001, 1100 , TO_DATE('07/01/2013','MM/DD/YYYY') , 0218 );
INSERT INTO  
XX_ORD_QNTY (INT_ID , ORD_QNTY , ORD_DATE , ORD_ID) VALUES ( 1002, 1500 ,TO_DATE('07/15/2013','MM/DD/YYYY') , 0218 );
INSERT INTO 
XX_ORD_QNTY (INT_ID , ORD_QNTY , ORD_DATE , ORD_ID) VALUES ( 1003, 1250 ,TO_DATE('07/13/2013','MM/DD/YYYY') , 0224 );
INSERT INTO 
XX_ORD_QNTY (INT_ID , ORD_QNTY , ORD_DATE , ORD_ID) VALUES ( 1004, 700 , TO_DATE('07/1/2013','MM/DD/YYYY') , 0224 );
INSERT INTO 
XX_ORD_QNTY (INT_ID , ORD_QNTY , ORD_DATE, ORD_ID) VALUES ( 1005, 1150 ,TO_DATE('07/10/2013','MM/DD/YYYY') , 0224 );
INSERT INTO 
XX_ORD_QNTY (INT_ID , ORD_QNTY , ORD_DATE , ORD_ID) VALUES ( 1006, 500 , TO_DATE('07/17/2013','MM/DD/YYYY') , 0388 );
INSERT INTO 
XX_ORD_QNTY (INT_ID , ORD_QNTY , ORD_DATE , ORD_ID) VALUES ( 1007, 350 , TO_DATE('07/01/2013','MM/DD/YYYY') , 0388 );
INSERT INTO 
XX_ORD_QNTY (INT_ID , ORD_QNTY , ORD_DATE , ORD_ID) VALUES ( 1008, 550 , TO_DATE('07/04/2013','MM/DD/YYYY') , 0388 );
INSERT INTO 
XX_ORD_QNTY (INT_ID , ORD_QNTY , ORD_DATE , ORD_ID) VALUES ( 1009, 350 , TO_DATE('07/13/2013','MM/DD/YYYY') , 0388 );


COMMIT;

Expected results of the SQL:

ORD_ID | TOTAL_QNTY

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

0218 |   16900

0224 |   9850 (9 * 700 + 2 * 1100 + 1250)

0388 |   7000 (3 * 350 + 8 * 550 + 3 * 350 + 500)

I thought to store the previous values and previous dates to calculate the basis of this, could just point me in the right direction please.

Thanks in advance.

Hello

Whenever you have a question, please post a small example data, the (correct) results you want from this data, as well as an explanation of how you get these results from these data.

If the sample data was published earlier in the same thread, just say it; There is no need to post again exactly the same.

If the results depend on the parameters (for example p_date1 and p_date2) then after two or three different sets of parameters and the results you want from the same data of sample for each game.

It's the resulrars that you want from the data of sample you posted earlier, given parameters July11, 2013 and 25 July 2013?

ORD_ID TOTAL_QNTY
---------- ----------
218 5900
224 3550
388 2150

Here's a way to get these results:

WITH params AS
(
SELECT TO_DATE (11 July 2013 ", ' MM/DD/YYYY') AS p_date1
, TO_DATE (15 July 2013 ", ' MM/DD/YYYY') AS p_date2
OF the double
)
got_n_days AS
(
SELECT q.ord_qnty, q.ord_id
, The LEAST (NVL (in ADVANCE (q.ord_date) OVER (PARTITION BY q.ord_id
ORDER BY q.ord_date
)
q.ord_date + 1
)
p.p_date2 + 1
) - GREATEST (q.ord_date
p.p_date1
) AS n_days
OF xx_ord_qnty q
CROSS JOIN params p
)
SELECT ord_id
, SUM (ord_qnty * n_days) AS total_qnty
OF got_n_days
WHERE n_days > 0
GROUP BY ord_id
ORDER BY ord_id
;

Tags: Database

Similar Questions

  • Help in the calculation of the Total Cycle time in days

    All,

    How to calculate the total duration in days... I have the start date, Date added, Date of the assignment and the Date of the seller

    Concerning

    number of days between the Start Date and Date added:

    TIMESTAMPDIFF (SQL_TSI_DAY, StartDate, AddedDate)

    The same model for others...

  • Check box adds to the Total

    Hey there,

    Anyone happen to know if there is a script so that when a box is checked, it adds the correlation price altogether?

    Screen Shot 2016-06-21 at 8.48.08 AM.png

    Thanks in advance!

    JW

    Use the code I provided the custom calculation of the total field script.

    I had assumed that the prices are fixed. If indeed they are dynamic and you have a text field for each award, then you can use something like this:

    var total = 0;
    if (this.getField("CheckBox1").value!="Off") total+=Number(this.getField("Price1").value);
    if (this.getField("CheckBox2").value!="Off") total+=Number(this.getField("Price2").value);
    if (this.getField("CheckBox3").value!="Off") total+=Number(this.getField("Price3").value); // etc.
    event.value = total;
    
  • SQL for the calculation of the salary

    Version: 11.2

    Permanent employees get monthly salary, contract workers get only commission.
    Some permanent employees such as PETER and JOHANN get salary and Commission


    I want to find the total amount paid to permanent and non-permanent.

    The computation of the total, for employees who receive the salary and Commission as PETER and JOHANN, I want to ignore the Commission and considers that pay them for the calculation of total compensation.
    ie. When computing the total amount paid to all these employees
    
        I want to ignore commision of 400 received by PETER 
        and
        I want to ignore commision of 1000 received by  JOHANN
    That is to say. The Total amount paid will be: 18 500

    create table pay_master (emp_type varchar2(50) , empname varchar2(50), salary number , comm number );
    
    
    insert into pay_master values ( 'PERM', 'KAREN' , 2000, 0 );
    insert into pay_master values ( 'PERM', 'HANS'  , 3000, 0 );
    insert into pay_master values ( 'CONTRACT', 'KEITH'  , 0, 1000 );
    
    insert into pay_master values ( 'CONTRACT', 'ABDUL'  , 0, 2000 );
    insert into pay_master values ( 'PERM', 'KRISHNA'  , 1000, 0 );
    insert into pay_master values ( 'CONTRACT', 'CHENG'  , 0, 1500 );
    insert into pay_master values ( 'PERM', 'PETER'  , 5000, 400 );
    insert into pay_master values ( 'PERM', 'JOHANN'  , 3000, 1000 );
    
    
    col EMP_TYPE format a10
    col EMPNAME format a10
    
    SQL> select * From pay_master order by empname;
    
    EMP_TYPE   EMPNAME        SALARY       COMM
    ---------- ---------- ---------- ----------
    CONTRACT   ABDUL               0       2000
    CONTRACT   CHENG               0       1500
    PERM       HANS             3000          0
    PERM       JOHANN           3000       1000           ---------------> Ignore this commision when calculating the total pay
    PERM       KAREN            2000          0
    CONTRACT   KEITH               0       1000
    PERM       KRISHNA          1000          0
    PERM       PETER            5000        400           ---------------> Ignore this commision when calculating the total pay
    
    8 rows selected.
    
    SQL> select EMPNAME , salary+comm from pay_master order by empname;
    
    EMPNAME    SALARY+COMM
    ---------- -----------
    ABDUL             2000
    CHENG             1500
    HANS              3000
    JOHANN            4000
    KAREN             2000
    KEITH             1000
    KRISHNA           1000
    PETER             5400
    
    8 rows selected.
    
    SQL> select sum(salary+comm) from pay_master;
    
    SUM(SALARY+COMM)
    ----------------
               19900
    
    
    Expected output from the SQL with the above mentioned logic is 18500
    How can I do this in SQL? I think that I can't use CASE here statement because the CASE statement works only in a single column. Right?

    Hello

    J.Kiechle wrote:
    ... I think that I can't use CASE here statement because the CASE statement works only in a single column. Right?

    A CASE results in a single value expression. It may depend on any number of columns (that is, of reference): 0, 1, 2, 3 or more.

    For example, the following is based on 2 columns, x and y:

    CASE
        WHEN  x > y
        THEN  x
        ELSE  y
    END
    

    which is just another way to get the same results that

    GREATEST (x, y)
    

    You can use either of the foregoing, for your problem (assuming that the salary and the Commission are always 0 or more).

    Published by: Frank Kulash, Sep 21, 2012 05:40

  • SQL query to find the total number of source based nonsource passangersbetween source and destination station and passenger station on the same chekindate

    Hello

    SQL query to find the total number of source based nonsource passangersbetween source and destination station and passenger station on the same chekindate.

    Please help on this script and let me know if you need more details.

    ---

    You use a SELECT statement.  Let me know if you need more details.

  • Calculation of the break time lunch after midnight = total number of minutes?

    Hello, Im new to Livecycle please bare with me. I have a sheet that Im having trouble with.  I searched and searching the net for answers and I did not yet find something to help solve my problem.

    Here's my problem, Im trying to calculate the total number of minutes, an employee took a lunch break. I have a script that works fine for a normal move 08:00 to 17:00. The problem is that I can't him crossed e.g. 23:45 to 12: 15 to 12:30, calculate rather im get 24 h 30.

    Here is my script if anyone out there can you please help me with this id very happy, so far its been a nightmare, try to understand this.

    If (HasValue (morningshift. Row4.Cell5) and HasValue (morningshift. Row4.Cell6)) then

    var start = Floor (Time2Num (morningshift. Row4.Cell5.FormattedValue, "h: mm A") / 1000)

    finishing of the Floor (Time2Num(morningshift.) = var Row4.Cell6.FormattedValue, "h: mm A") / 1000)

    var = regular arrival - departure

    var Min = Right (Concat ('0', Mod (Floor(regular / 60), 60)), 2)

    var h = Right (Concat ("0", ground (regular /(60*60))), 2) Concat(Hrs,":",Min)

    endif

    I had a little problem with something similar.  However, I finally came up with a simple solution.  I just snuck in an if statement in my line of code that adds 24 hours to the end time, when the start time is the largest number. The way which you extracted and formatted the calculation time seems different from mine, but the idea should still work even if you have to make small adjustments.

    Code to get the start time and end in seconds

    ..

    Look for the late shift (86400 = 24 h in seconds)

    If (fStart > = fend) {}

    fend += 86400;

    }

    ..

    Calculate and display the result

  • How to get the total number of pages have been printed using the pl/sql

    Dear all,

    I want to store the total number of physical pages printed in a database table, how could retrieve the value of the total number of pages.


    I am using Oracle 6i report

    thnxxx in advance :)

    At the end of your report (i.e. After all the images from your data model), place a dummy field. You can get the page number with srw.get_page_num in the trigger of the format of this field. Since it is the last field of your report, it is also the last page number.

  • How to make calculations on the grid... salary total and so on?

    Hi Experts,

    I use the Employee table and I it shows as a grid in the jspx page.

    When I add or change the value of the SALARY column, the total salary of the employees in the grid should be updated in the State of the panelcollection...

    I just tried to use ValueChangeListener and I am an iteration values and adding the wage and doing other things...

    Is it an effective way to do this...?


    Please suggest some ideas...


    Kind regards
    GOPs

    Hello

    I guess you can also use groovy

    See page 12 of this link. Might be useful
    http://www.Oracle.com/technetwork/developer-tools/jdev/introduction-to-Groovy-128837.PDF

    Kind regards
    Briant

  • -How the calculations on the Apex?

    I have 2 tables: A and B. A is related to B with 1:m relationship.

    Table stores the information about the quote - name, address, total cost of construction quote.

    Table B stores the list of services for a particular quote (linked to table A) - as the service quote (bathroom, kitchen, roof) , cost of the service, etc.

    There is a way to calculate the total cost of the "cost of service" column in table B, by editing 'report attributes' and checking the sum.

    But how would have received this amount (for the cost of each service on table B for a particular quote) to be displayed in the 'total price' field on the table?

    Surely, there must be a way to link them together.

    I have to do it outside of the Apex on SQL?

    Newbie.

    Here is the picture to help you understand

     photo oraclesumcal.png

    I think that some (maybe pl/sql) sql calculation is required in the source box. Maybe I should do it on sql first. I need advice on how to do it.

     photo oraclesumcal2.png

    How about this, you will need to use the Q_QUOTE_ITEM fk

    Select sum (PRICE_QOTD) from Q_QUOTE_ITEM

    where Q_fk_quoteno =: P7_QUOTE_NO

    There is no 'total price' field for the moment so im using notes on Q_Quote.

    you mean an item of type "View only" to display the total?

  • Calculation of the IR, aggregate functions

    Hi all

    I generated an interactive report which must show counties, totals and averages.

    My question is something like below.

    5 1000 200 Row1
    10 2000 200 row2
    row3 5 500 100
    Total: 20 3500 175 (166)

    Let's say that the column with values 5,10,5 indicates the number of employees.
    column with values 1000,2000,500 are the total salaries of employees (respectively)
    column with the 200,200,100 values are averages. (which i use interactive report CALCULATION for values).

    the last line shows the totals and the avg (last row-last column)

    I have to get 175 which is right, but I'm 166 (using inbuild functionality)
    what his weight is summing the values 200,200,100 and then plunged by # of lines.
    I would like to see 3500/20 to this place.

    How do I get there?

    I use Apex 4.1 and 10g DB.


    Thank you
    Daniel

    Rather than rely on apex aggregated in this example, you can achieve with SQL

    Select deptno,
    Count (*),
    Sum (SAL),
    Round (AVG (SAL), 2)
    WCP
    GROUP BY deptno
    UNION
    Select deptno NULL,
    Count (*),
    Sum (SAL),
    Round (AVG (SAL), 2)
    WCP
    ORDER BY 1

    The result is...
    10 3 8750 2916.67
    20 5 10875 2175
    30 6 9400 1566.67
    -14 29025 2073.21

    It may be useful

    Chandra

    Published by: cmovva on February 9, 2012 11:52

  • Problem with the total amount of in.

    Hi people,

    I developed a report on the orders (po) buying and at the level of the line, I took po_amount IE
    po_amount = line_qty * unit_price, but this isn't the total amount, I need.

    Here I should consider taxes, then localized i.e. him total amount = taxes * po_amount that the above would be my total and these depend on the currency_code for example :-USD or INR, and for each line-in. There is an amount of tax.

    Without manipulating my custom query (I won't bother him), through discoverer can I write a pl/sql function for the column of taxes and perform a calculation using this function and add an additional column that shows the total amount for me.

    Is this possible? If yes how can we do? any1 can explain briefly.

    Thank you
    Kind regards
    Murielle.

    Hello

    When you create calculation make sure you select the function in the list of available features and then select the po_line_id in the list of available items. If you type just the function and element in the calculation box it probably won't work.

    Rod West

  • How to get the total of the multiple products of cells

    I want to save my money on the balances of the hand for different days of the year and see if I can develop a trend and reduce my expenses. I can easily make a cell inside of my table that tells me how many I have a kind of money (20 of 5 cents, 9 $2, 3 50 $, etc.) for today (aid = Lookup), the day where I'm looking for my document. This can be used to show me a trend, however, if I want to do another column that keeps track of this total, so that I can use it as a reference to a line chart elsewhere.

    My problem is that when I want to many the last row of cells (filled with the types of currency) by their amounts (20, 9, 3), I have to do for each cell, and if I try to fill it, numbers changes the cells I want it multiply so that now the two amounts are multiplied, rather than the independent form and variable amount.

    My question is: which formula can be used to multiply each B1, C1, D1 etc. with the appropriate..., C2, B2 or B3 and C3... etc, so that I can fill and then also for other cells in column N.

    Hi Kasai,

    SUMPRODUCT is your friend here.

    The totals are in column N.

    N2 and filled down: = IF (COUNT(B2:M2)<>SUMPRODUCT($B$1:$M$1,$B2:$M2))

    The IF part removes the calculation of this row if no number has been involved in any of columns B to M.

    If everything has been entered, the IF condition returns FALSE and the calculation of SUMPRODUCT (in "BOLD") is done.

    I noticed that you included a piece of 20 cents in the list in the upper part, which has awakened my curiosity. Is this typo, or is it a country whose currency is denominated in "dollars" which is a coin circulating 20 cents worth?

    Kind regards

    Barry

  • Rapid calculation of the exponential decay constants

    Hi all

    I try to develop a routine that quickly calculates the exponential decay of a given waveform constant.  I use two different techniques, dealing with the calculation of the directions and another using corrects successive integration (LRS).  The two usually give the correct time for the input waveform even constant with a significant amount of noise.  The LRS solution is significantly less sensitive to noise (desirable), but much more slowly (DFT computations run the order of 10s of microseconds for a waveform pt 1000, while the LRS, such that it is coded in Labview, running at about 1.5 ms).  The LRS technique has been developed by researchers at the George Fox University in Oregon, and they claim that they could perform some computation time on the order of 200 US for both techniques.  I have been unable to reach this time with the LRS technique (obviously) and attempted to use a node of the library Call to call a dll compiled this code in C.  However, at best, I get a growth factor 2 in speed.  In addition, additional calculations using the dll seem to be additive - i.e. for four calculations similar running in the same structure with no dependence on each other, the total computation time is about 4 times that of one.  In my case, this is not enough because I try to calculate 8 x to 1kH.

    Looking through the discussion, I have been unable to determine if I should wait for a performance for C gain well written on Labview well written (most seem to ask why you want to do something external).  In any case, I join the code, then you can be the judge as to if it's well-written, or if there is no improvement in performance.  The main function is the Test analysis Methods.vi that generates a wave exponential scale, offset and noise and then the decay constant tau is calculated using the VI is Tau.vi.  In addition, I am attaching the C code as well as the dll for solving the equations of LRS.  They were coded in Labview 8.6 and the C has been encoded using the latest version of Visual C++ Express Edition from Microsoft.  Themain VI uses the FPGA VI module ' Tick count to determine the rate of computation in microseconds, so if you do not have this module you should remove this code.

    Any thoughts are appreciated.  Thanks, Matt

    Hi Matt,

    After changing the summation loop in your calculation of CWR, the routine runs as fast (or faster) than the variants of the DFT... Anyway: check the results to be sure it is still correct.

  • Question about the accuracy of the Total remaining time for battery in Power Meter

    Mr President.

    I checked several laptops that are of the same model, one of them cannot display "Total time remaining" in the power meter. Even other laptops may display, but the values are equivocal. Sometimes the 'remaining power' is 80%, but 'Total remaining time' is 1H20Mins. And sometimes, the "remaining power 'is 75% ', but"the Total remaining time"is 1H30Mins.

    How Windows calculates the 'Total remaining time? I found what OS will have one or two minutes to display "Total remaining time" after I have the power cable plug-out.

    Which is appreciate to get your answer.

    Horky

    The remaining computing power comes from the numere questioning power management drivers and is a fairly complex calculation based on current usage (the amount of energy is consumed), the capacity of the battery (what total capacity is left and how fully charged is battery) and can also vary depending on what else is plugged into the USB port of the computer , what accessories (memory, video card, etc.) are installed, how good or bad, the battery is to maintain a charge and so on.  There is no particular reason to believe that maybe outside the right-out-of-the-box everything two laptops will show the same calculation even if they are all the same brand and model.

    "Horky.Chen" wrote in the new message: * e-mail address is removed from the privacy... *

    Mr President.

    I checked several laptops that are of the same model, one of them cannot display "Total time remaining" in the power meter. Even other laptops may display, but the values are equivocal. Sometimes the 'remaining power' is 80%, but 'Total remaining time' is 1H20Mins. And sometimes, the "remaining power 'is 75% ', but"the Total remaining time"is 1H30Mins.

    How Windows calculates the 'Total remaining time? I found what OS will have one or two minutes to display "Total remaining time" after I have the power cable plug-out.

    Which is appreciate to get your answer.

    Horky

  • Type [0] unknown calculation for the dynamic calculation. Only default agg/formula/time balance operations are managed.

    Hi all

    I came across this error last Monday. I tried all the recommendations and configurations and nothing seems to work to solve the problem.

    Here is the error message-

    [Game Sep 24 12:04:27 2015] Local, ARPLAN, ARPLAN, Ess.Tee@MSAD_2010/9240/Error (1012703)

    Type [0] unknown calculation for the dynamic calculation. Only default agg/formula/time balance operations are managed.

    [Game Sep 24 12:04:33 2015] Local, ARPLAN, ARPLAN, Ess.Tee@MSAD_2010/9240/Warning (1080014)

    Abandoned due to the State [1012703] [0x2e007c (0x56042d17.0xeadd0)] transaction.

    [Game Sep 24 12:04:33 2015] Local, ARPLAN, ARPLAN, Ess.Tee@MSAD_2010/8576/Warning (1080014)

    Abandoned due to the State [1012703] [0x40007d (0x56042d18.0x781e0)] transaction.

    [Game Sep 24 12:04:34 2015] Local, ARPLAN, ARPLAN, Ess.Tee@MSAD_2010/736/Info (1012579)

    Total time elapsed Calc [Forecast.csc]: [621,338] seconds

    The script I'm running-

    SET CACHE HIGH;

    SET MSG SUMMARY;

    LOW GAME REVIEWS;

    UPDATECALC OFF SET;

    SET AGGMISSG

    GAME CALCPARALLEL 2;

    SET CREATEBLOCKONEQ

    SET HIGH LOCKBLOCK;

    FIX ('FY16', 'Final', 'Forecasts', '11 + 1 forecasts', 'prediction of 10 + 2', '9 + 3 forecast', '8 + 4 forecasts', "forecast 7 + 5", "6 + 6 forecast", "forecast 5 + 7", 'forecast of 4 + 8', '3 + 9 forecast', 'forecast 2 + 10', '1 + 11 forecasts')

    DIFFICULTY (@IDESCENDANTS ('entity'))

    CALC DIM ("account");

    ENDFIX

    DIM CALC ("entity", "Currency");

    ENDFIX

    In the essbase.cfg I have already included-

    NETDELAY 24000

    NETRETRYCOUNT 4500

    /Calculator cache settings

    CALCCACHEHIGH 50000000

    CALCCACHEDEFAULT 10000000

    200000 CALCCACHELOW

    Lockblock/set limits

    CALCLOCKBLOCKHIGH 150000

    CALCLOCKBLOCKDEFAULT 20000

    CALCLOCKBLOCKLOW 10000

    Please suggest if there is a way to fix this error. I get a similar error for other calculations as well.

    Kind regards

    EssTee

    And you are positive that no one came in a new Member at level 0 as dynamic Calc?

    What are the versions do you use?

Maybe you are looking for

  • iMac with bootcamp only starts 10 W

    I used Bootcamp to install W 10 on my iMac (El Capitan, 2012) It worked correctly, although I didn't see the icon in the bar of sys Windows Bootcamp. Until recently, I could change the OS by pressing the 'Option' key at the start of the IMac. But kno

  • View image icon file

    Today is the first time that I had this problem.  When selecting to display the large icon of my photos - I get the icons of the program logo, not my photos. Tried each photo progam I have and get the same results, not my photo images, just the progr

  • boot cant to install CD and windows shows 2 installs

    installation of Windows I wanted to reinstall windows xp. but there was something wrong so I couldn't start windows from cd! Although I made any sense, anyway I did it another way by installing windows on D: drive, so I can format C; drive and then i

  • Can I just move my router from modem to modem?

  • BlackBerry Smartphones bb9300 freezes

    My 9300 BB freezes 3/4 times a day. This started only after I updated my software via the PC, office of BB THAT I did a few days ago. He also tells me OPEN SPACE: 15 MB. Before the update, is 32 MB?