Columns of the sum of different record count of joined tables

I have a problem with a query, please help.

I have two tables:
create table rec_a (key_code varchar(20),
                TOT_AMT varchar(20),
                INV_AMT varchar(20))
/ 
 
create table rec_B (key_code varchar(20),
                INVOICE_AMT varchar(20),
               PAID_AMT varchar(20))
/ 
 
insert into REC_A values (123123,  1168182.16, 1168182.16);

insert into REC_B values (123123, 205699.04,205699.04);
insert into REC_B values (123123,130912.78,130912.78);
insert into REC_B values (123123, 81622.87,81622.87);
insert into REC_B values (123123, 438032.43,438032.43);
insert into REC_B values (123123, 159936.17,159936.17);
insert into REC_B values (123123, 151978.87,151978.87);
 
Table 1
KEY_CODE TOT_AMT INV_AMT
123123 1168182.16 1168182.16


Table 2
KEY_CODE INVOICE_AMT PAID_AMT
123123 205699,04 205699.04
123123 130912,78 130912.78
123123 81622,87 81622.87
123123 438032,43 438032.43
123123 159936,17 159936.17
123123 151978,87 151978.87


I wrote a query to sum up all the areas (tot_amt, inv_amt, invoice_Amt, paid_amt)
SELECT B.key_code,sum(A.invoice_amt),sum(a.paid_amt),SUM(b.tot_Amt),SUM(b.inv_amt) FROM rec_a B, rec_b A WHERE A.KEY_CODE=B.KEY_CODE AND B.KEY_CODE in ('123123')
group by B.key_code
I got this:

KEY_CODE SUM (A.INVOICE_AMT) SUM (A.PAID_AMT) SUM (B.TOT_AMT) SUM (B.INV_AMT)
123123 1168182.16 1168182.16 7009092.96 7009092.96

But I expected this

KEY_CODE SUM (A.INVOICE_AMT) SUM (A.PAID_AMT) SUM (B.TOT_AMT) SUM (B.INV_AMT)
123123 1168182.16 1168182.16 1168182.16 1168182.16


Can someone help me out here?

Thank you

Published by: 1003064 on April 29, 2013 03:19

Hello

1003064 wrote:
I have a problem with a query, please help.

I have two tables:
Table 1
KEY_CODE TOT_AMT INV_AMT
123123 1168182.16 1168182.16

Table 2
KEY_CODE INVOICE_AMT PAID_AMT
123123 205699,04 205699.04
123123 130912,78 130912.78...
123123 81622,87 81622.87
123123 438032,43 438032.43
123123 159936,17 159936.17
123123 151978,87 151978.87

I wrote a query to sum up all the areas (tot_amt, inv_amt, invoice_Amt, paid_amt)

SELECT B.key_code, sum (a.invoice_amt), sum (a.paid_amt), SUM (b.tot_Amt), SUM (b.inv_amt) FROM rec_a A, rec_b B WHERE A.KEY_CODE = B.KEY_CODE AND B.KEY_CODE in ('123123')
B.key_code group

I got this:
KEY_CODE SUM (A.INVOICE_AMT) SUM (A.PAID_AMT) SUM (B.TOT_AMT) SUM (B.INV_AMT)
123123 1168182.16 1168182.16 7009092.96 7009092.96

But I expected this

KEY_CODE SUM (A.INVOICE_AMT) SUM (A.PAID_AMT) SUM (B.TOT_AMT) SUM (B.INV_AMT)
123123 1168182.16 1168182.16 1168182.16 1168182.16

Thus, the last 2 columns must be exactly what is stored in table1? Then either
b include these columns in the GROUP BY clause and not to use the SUM,
(b) the GROUP BY on rec_a alone, separately, can't join the results to the rec_b, or
(c) using MIN or MAX, instead of SUM. (Anyone. Since there is only one value, MIN will be the same as MAX.)

Here is an example of (a):

SELECT    B.key_code
,       sum (a.invoice_amt)     AS sum_invlice_amt
,       sum (a.paid_amt),     AS sum_paid_amt
,       b.tot_Amt
,       b.inv_amt
FROM        rec_a          A
,        rec_b          B
WHERE        A.KEY_CODE     = B.KEY_CODE
AND        B.KEY_CODE      in ('123123')
group by  B.key_code
,            b,tot_amt
,       b.inv_amt
;

I hope that answers your question.
If not, post a small example of data (CREATE TABLE and only relevant columns, INSERT statements) for all of the tables involved and the results desired from these data.
Point where the above query is to produce erroneous results, and explain, using specific examples, how you get the right results from data provided in these places.
Always say what version of Oracle you are using (for example, 11.2.0.2.0).
See the FAQ forum {message identifier: = 9360002}

Tags: Database

Similar Questions

  • The analysis of a column of delimeted and then summarizing Records counties

    Hi all - I'm doing some different things with a SQL query, and it's a bit beyond my skill level.

    1. The first thing I do is to analyze a varchar2 column in a table that represents the "tags" and remove the unique values. The tags are either space, comma or semicolon delimited and sometimes there is a space before and/or after the delimiter.
    2. The second thing I have to do is to summarize the number of records per unique label.

    For example:

    create table tags (record_id number, tags varchar2(120)); --Assume record_id is the primary key
    
    
    insert into tags (record_id, tags) values (101, 'Apples, Bananas');
    insert into tags (record_id, tags) values (102, 'Apples:Oranges');
    insert into tags (record_id, tags) values (103, 'Bananas:Oranges');
    insert into tags (record_id, tags) values (104, 'Bananas Grapes');
    insert into tags (record_id, tags) values (105, 'Bananas:Oranges:Apples');
    insert into tags (record_id, tags) values (106, 'Apples Grapes');
    commit;
    

    In the end, the result of the query that I need is:

    4 apples

    Bananas 4

    3 oranges

    Grapes 2

    So something like this, except of course I can't hard code tag value and I would need the request to pick up every single tag values:

    select 'Apples', count(record_id) from tags where tags like '%Apples%' group by 'Apples';
    
    'APPLES' COUNT(RECORD_ID)
    -------- ----------------
    Apples                  4 
    

    Thanks in advance for your suggestions,

    John

    Hello

    Relational databases are designed to have 1 single piece of information in each column of each row, not some kind of list delimited with a variable number of elements.  It is therefore designed a basic for the database he called first normal form.  This, and a lot of other jobs will be much simpler and more effective if you standardize your table.

    If you're stuck with the current design, here's a way to do it:

    WITH got_tag AS

    (

    SELECT REGEXP_SUBSTR (tags

    , '[^, :]+'

    1

    LEVEL

    ) As a tag

    Tags

    CONNECT BY LEVEL<= regexp_count="" (tags,="" '[^,="">

    AND record_id = record_id PRIOR

    AND PRIOR SYS_GUID () IS NOT NULL

    )

    SELECT tag

    AS cnt ACCOUNT (*)

    OF got_tag

    GROUP BY tag

    ORDER BY tag

    ;

    Output:

    TAG CNT

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

    4 apples

    Bananas 4

    Grapes 2

    3 oranges

    As you can see, almost all the complexity of this query is in the got_tag of the subquery, which puts each individual tag on a separate line, that is how it should be stored in the first place.  If you had a table standard, you wouldn't need to do all this.

  • calculation of ratios and rounding - how the sum of last record to give 1

    I'm putting in a single query to calculate the reports for an unknown number of records. I want to turn the ratios to 5 decimal places and I want the total reports of equal to 1.

    for example

    If I have 3 folders with Qty total overal 4,5,6 is 15
    I note 3 lines
    Round (4/15.5),
    Round (5/15.5),
    Round (6/15.5)

    but I want to ensure total = 1
    so I will try to do something like

    Round (4/15.5),
    Round (5/15.5),
    1 - round(4/15,5) - round(5/15,5)

    can someone help show me the sql construction? I've been trying and failing using where clause

    of course this example would add to 1 but other unknown ratios may not match up to 1.

    Published by: user12154024 on November 2, 2009 22:32

    Hello 12154024,

    Welcome to the forum. May not be a more elegant solution, but it shows how it works step by step

    WITH t AS (
    SELECT 4 n FROM dual
    UNION ALL
    SELECT  5 n FROM dual
    UNION ALL
    SELECT 6 n FROM dual
    )
    ,t1 AS (
    SELECT  n
           ,ROUND(RATIO_TO_REPORT(n) OVER (),5) AS rr
           ,COUNT(n) OVER () AS c
           ,ROW_NUMBER() OVER (ORDER BY n) AS rn
    FROM    t
    )
    ,t2 AS (
    SELECT  n
           ,rr
           ,SUM(rr) OVER (ORDER BY n) s
           ,c
           ,rn
    FROM t1
    )
    SELECT  n
           ,rr
           ,CASE WHEN c = rn THEN
                rr + (1 - s)
            ELSE
                rr
            END rr2
           ,s
    FROM    t2
    ORDER BY rn;
    
    N   RR        RR2       S
    --- --------- --------- --------
    4   0.26667   0.26667   0.26667
    5   0.33333   0.33333   0.6
    6   0.4       0.4       1        
    
    3 rows selected
    

    The part "WITH t AS" generates data
    T1 calculate the ratio, counts the number of records and signs a current issue
    T2 to calculate a cumulative ratio
    the last part takes these data and for the last record (number = count running) it allows to adjust the ratio.

    You can see if you are using other data

    WITH t AS (
    SELECT 4.78 n FROM dual
    UNION ALL
    SELECT  5 n FROM dual
    UNION ALL
    SELECT 6 n FROM dual
    )
    ...
    
    N    RR       RR2      S
    ---- -------- -------- --------
    4.78 0.30292  0.30292  0.30292
    5    0.31686  0.31686  0.61978
    6    0.38023  0.38022  1.00001  
    
    3 rows selected
    

    Concerning
    Marcus

  • By comparing the number of different records of different tables of databases with Production DB

    Hello

    I updated 6 paintings of DEVEOPMENT and QA database production databases.

    According to the request of the customer, I want to create a stored procedure to compare the number of tables with the number of Production DB records.

    Could you please suggest me a better way to do this.

    example: select count (*) in the emoployee@Devlopment_Database.  -I want to check with select count (*) from employee@Procuction_Database

    Select count (*) in the emoployee@QA_Database.                 -I want to check with select count (*) from employee@Procuction_Database

    Thank you

    Vincent

    If so, your question is asking how to create a database link?

    CREATE THE DATABASE LINK

  • Weighted average end days: how the sum in different currencies?

    Hello

    I have to introduce a new column named "averages weighted days late" in one of the models.

    It was easily handled by the code in the Oracle report: Aging Ar: calculated as <? If: SUM_PAYMENT < = 0? > 0 <? end if? > <? If: SUM_PAYMENT > 0? > <? SUM_W_DAYS_LATE div SUM_PAYMENT? > <? end if? > UX f

    The customer wants that this weighted means against the different currencies for a single client: How do I implement that?

    Example: Client A - average weighted days late:-16-20 in USD and EUR. = > report displays only the first currency - in this case EUR = >-16 (which is not what is expected)

    Logic: I need to run (-16) +(-20)/2. The logic is simple. However, where should I create this change? Also, this change must be connected to the period during which the report is run for / just for the money? I guess it's related at the same time.

    Thanks in advance

    and then divide it by the number of transactions.

    That's your logic? If yes then ok

    I don't know full logic

    And this must be done in the sql used in the xml file, I guess. Is there an easier option to calculate the end of days average weighted by a modification of the model code? Curious.

    If you already have some fares in the xml file to recalculate, then you can do so by model

    If you do not have the rate, then you can add it to xml format and then calculate by model

    or you can calculate in sql (as an example of data model) and then only show models

    How will be used it is your decision

  • Display two columns of the sum

    Hi all

    I am a beginner and need help on a requirement.

    I have a table.

    Level of ID data
    ----------------------
    1 TL 200
    1 BT 200
    1 TL 200
    1 BT 300
    2 TL 300
    BT 2 400

    I want to display:

    ID Sum (BT) Sum (TL)
    ----------------------------------
    1 500 400
    2 400 300

    Thank you very much.

    You have to change the table and column names.
    The column names that you use are reserved words of Oracle...

    select pk
    ,      sum(case
                 when lvl = 'BT'
                 then descr
                 else 0
              end
              )sumBT
    ,      sum(case
                 when lvl = 'TL'
                 then descr
                 else 0
              end
              )sumTL
    from   t
    group by pk;
    

    Output:

            PK      SUMBT      SUMTL
    ---------- ---------- ----------
             1        500        400
             2        400        300
    
    2 rows selected.
    
  • Dynamically set read-only columns in the tabular presentation at record levels

    Hello

    Is it possible to activate and deactivate fields at the level of the line in a tabular presentation... I use OFA to create a page that should give the possibility to activate and deactivate certain fields in the table on the fly...

    Here's the requirement:

    examples of data

    Item_code |   Review | Point Attrib1 | Article attrib2 | Article attrib3 | Columna | ColumnB

    1.234               100           A                         B                    _                  A               _

    1.235               100          B                              _                 B                 _                   A

    fields point attrib3 and Columnb should be read-only if the value of attrib1 point is A

    Even if point value attrib1 is B columna and attrib2 of the element must be read-only...

    I have PPR on item_attrb1 to manage the change of value in the attrib1 element, but I'm not able to make fields read only at the level of the line... Please help me if someone has work around this

    Is this possible?

    Thank you

    Dilip

    Hello..

    It is possible. Made myself.

    You must use SPEL for this.

    Steps to follow:

    1. the Caisse one type of transitional say as Boolean column ReadOnly

    2 set the Readonly property for that column as ReadOnly

    (Syntax FRO SPEL-> {oa. VO. ReadOnly})

    3 al ' PPR after checking the status, the ReadOnly Anaïs value accordingly.

    .

    You can get the idea here.

    https://blogs.Oracle.com/manojmadhusoodanan/entry/hiding_an_item_conditionally_through

  • the substitution of the format of the value on the column of the sum

    I have a report from the region, when I summarized a column total is posted with a specific format of theme.
    For me, it will come out as "BOLD" / black and a font size. Is it possible to replace? and how?

    Thank you.

    Hello

    >
    BTW, im still using v2.0
    >

    That explained a lot. Some of these options overrides string for report models did not exist in older versions of the Apex, so you wouldn't have a region ID to identify the report area.

    But we can do it manually.

    On the report definition, in the header of the region, Supplement:

    <div id="MyReport">
    

    and in the foot of the region, Supplement:

    </div>
    <script type="text/javascript">
    var outertable = document.getElementById("MyReport");
    var innertable = outertable.getElementsByTagName("TABLE")[1];
    var rs = innertable.rows;
    var lastrow = rs[rs.length-1];
    if (lastrow.cells[0].firstChild.firstChild.nodeValue == 'TOTAL')
    {
     rs[rs.length - 1].style.backgroundColor = "red";
     rs[rs.length - 1].style.color = "yellow";
    }
    </script>
    

    This allows us to put a div around the area and then get the second table in this (considering the fact that a report is a table in a table) - subsequently, the javascript code is the same.

    Andy

  • Using the function PLSQL return Record Type Index of Tables in ADF

    I have a PLSQL function, a return type. My ultimate goal is to take this binary integer index Table and print it on the screen...

    CREATE OR REPLACE PACKAGE my_pkg IS
     
    TYPE t_col IS RECORD(
     
    i NUMBER,
     
    n VARCHAR2(30));
     
    TYPE t_nested_table IS TABLE OF t_col;
     
      FUNCTION return_table RETURN t_nested_table ;
    END my_pkg;


    OPTION 1:

    1) has anyone got best practices to accept plsql RECORDS returned by a function?

    Here is an example.

    http://adfpractice-Fedor.blogspot.SG/2013/01/working-with-PLSQL-procedures-in-ADF-BC.html

    But it will be a lot of work... first of all accept the results in a loop... then store in a temporary storage can be a few VO or global temporary table and then display them on the page


    OPTION 2:

    Using the functions PIPLELINED and use in the select statement.  While I can use this select statement in the SQL query to create VO... and drag and drop the VO...

    CREATE OR REPLACE PACKAGE my_pkg IS
     
    TYPE t_col IS RECORD(
     
    i NUMBER,
     
    n VARCHAR2(30));
     
    TYPE t_nested_table IS TABLE OF t_col;
     
      FUNCTION return_table RETURN t_nested_table PIPELINED;
    END my_pkg;


    select * from table(my_pkg.return_table);


    Wow... I'm so smart! .. really possible?  who is the best/possible/recommended option?

    I'm sure that will be the question most read by many who wants to use PLSQL instead of JAVA to the treatment and CHOSEN to use only to display the output of the PLSQL functions or procedures.


    Thank you

    Rahul


    Dario

    Do you mean the scope of the defined Type pkg will be finished?

    I created guy outside the pkg as 'Create Type' if it works in this case?

    Yes, level objects schema (created with "create or replace type...") can be used in java and this can work.

    I think that then the scope of this TYPE will remain until the user session passes.

    Object definitions is not worn, but have their bodies.

    So, if you instantiate the data level object type schema in a plsql function, scope of this object is this function.

    Of course, if you instantiate the object as a variable package, then life of this object is equal to the lifetime of the package (which usually equals life of session db).

    Dario

  • How to get the last row and the sum of all columns in a query

    Hello

    is there a way to get the last record for a column and the sum of all the Archives to another column in the same query.

    Best regards

    You must set your needs correctly volunteers to help here...

    Your data are not good enough to bring you a precise solution. Purpose, you do not have a column, which draws a distinction between the first and the last entry.

    The solution becomes easy based on your design.

    I introduced a grouping called 'id' column and a time column called 'time_of_insert' (only this way you can say with confidence that you can differentiate between the first and last (also a foolproof solution) - you can possibly use sequence (instead of date but if you say that you can insert two lines at the same time) ((and then likely sequence would be a better choice to differentiate instead of a timestamp field) etc...)

    With your sample data, something like this can be done to get the desired results.

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

    WITH dataset AS

    (SELECT 1 id, 10 used, 8 remain, systimestamp + 1/24 time_of_insert FROM DUAL

    UNION ALL

    SELECT the 1 id, 1, 7, systimestamp + 2/24 FROM DUAL

    UNION ALL

    SELECT the id 1, 2, 5, systimestamp + 3/24 FROM DUAL

    UNION ALL

    SELECT 1 id, 1, 0, systimestamp + 4/24 FROM DUAL

    UNION ALL

    SELECT 1 id, 0, 0, systimestamp + 5/24 FROM DUAL

    UNION ALL

    SELECT the 1 id, 1, 4, systimestamp + 6/24 FROM DUAL)

    SELECT *.

    (SELECT SUM (used) ON sum_all)

    FIRST_VALUE (stay)

    COURSES (PARTITION BY id ORDER BY time_of_insert DESC)

    last_row

    Of THE dataset)

    WHERE ROWNUM = 1;

    Output:

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

    SUM_ALL LAST_ROW

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

    15                  4

    See you soon,.

    Manik.

  • How to perform an addition of column values in an insert query that would insert in the 3rd column, and the values how to insert into another table.

    I have two tables (2) RESULT TAB (1)

    CREATE TABLE TAB

    (

    NUMBER OF SNO

    A NUMBER,

    B THE NUMBER.

    NUMBER OF THE SUM

    );

    CREATE AN ARRAY OF RESULT

    (

    NUMBER OF SNO

    NUMBER OF THE SUM

    )

    my doubt is:

    (1) I want to insert a table TAB, my question is how to insert a column to the SUM using the column A AND B... Here im adding two values of the column and store result in the AMOUNT column.

    SNO   A  SUM           

    1 100 150 250

    2 300 100 400

    I want to like this, it is possible with single insert query?


    (2) at the time of the insertion TAB of values that SNO, and the values of table TAB $ insert in the table of RESULTS... is it possible these two inserts at the same time?

    in fact, im using another this table.fro TAB and easy to understand I write like that, please solve this problem

    First, you post in the wrong forum as this one is only for Oracle's SQL developer tool. So you might ask your question in the general forum of SQL.

    Second, you might solve your problems with bind variable:

    Insert tab

    (sno, a, b, sum)

    values

    (: SNO,: A: B: A + B :))

    You should not use sum as column name because it is a reserved word.

    More you cannot insert into two different tables with a single SQL, but you can use PL/SQL to do this:

    Start

    insert into tab values (: SNO,: A: B: A + B :);)

    insert into result values (: SNO,: A + B :);)

    end;

    If you meet sno from a sequence, you could do something like this:

    Start

    insert into values tab (seq_sno.nextval,:,: B,: A +: B) return sno in: SNO.

    insert into result values (: SNO,: A + B :);)

    end;

    Hope that helps,

    dhalek

  • Addign a computed column of the record count in table external

    Hello

    I have a csv file that is loaded using the external table. My need is to give a number to each record in the file and save it in one of the extra column in the table, can anyone suggest how it is possible?

    The structure of the file is:
    $cat emp.txt
    7369,SMITH,CLERK,7902,12/17/1980,800,,20
    7499,ALLEN,SALESMAN,7698,2/20/1981,1600,300,30
    7521,WARD,SALESMAN,7698,2/22/1981,1250,500,30
    7566,JONES,MANAGER,7839,4/2/1981,2975,,20
    7654,MARTIN,SALESMAN,7698,9/28/1981,1250,1400,30
    7698,BLAKE,MANAGER,7839,5/1/1981,2850,,30
    7782,CLARK,MANAGER,7839,6/9/1981,2450,,10
    7788,SCOTT,ANALYST,7566,12/9/1982,3000,,20
    7839,KING,PRESIDENT,,11/17/1981,5000,,10
    7844,TURNER,SALESMAN,7698,9/8/1981,1500,0,30
    7876,ADAMS,CLERK,7788,1/12/1983,1100,,20
    7900,JAMES,CLERK,7698,12/3/1981,950,,30
    7902,FORD,ANALYST,7566,12/3/1981,3000,,20
    7934,MILLER,CLERK,7782,1/23/1982,1300,,10
    
    --and the table structure is:
    
        CREATE TABLE TMP_emp_ext
        (
        EMPNO                                      NUMBER(4),
        ENAME                                              VARCHAR2(10),
        JOB                                                VARCHAR2(9),
        MGR                                                NUMBER(4),
        HIREDATE                                           DATE,
        SAL                                                NUMBER(7,2),
        COMM                                               NUMBER(7,2),
        DEPTNO                                             NUMBER(2)
        )
        ORGANIZATION EXTERNAL
          (  TYPE ORACLE_LOADER
             DEFAULT DIRECTORY DIR_N1
             ACCESS PARAMETERS
               ( records delimited  by newline
            fields  terminated by ','
            missing field values are null
           )
             LOCATION (DIR_N1:'emp.txt')
          )
        REJECT LIMIT UNLIMITED
        NOPARALLEL
        NOMONITORING
     /
    Now, my need is to give a number to each record... like the record from 7369, SMITH should be granted record n ° 1, 7499, ALLEN should be record No. 2 etc... can anyone suggest how it is possible?

    Thank you
    orausern

    T. Kyte write RECNUM should work in http://asktom.oracle.com/pls/apex/f?p=100:11:0:P11_QUESTION_ID:52733181746448 #52977916329285 because it is SQL * Loader syntax. However I've wasn't able to make it work with Oracle 10.2.0.4. But in case of errors of loading, you should find in _XXXXX.log the number of rejected records line (in my example it's the meaning of the 'line 2' "line 2"):

    erreur lors du traitement de la colonne EMPNO, la ligne 2, pour le fichier de données /tmp/emp.txt
    ORA-01722: invalid number
    
  • Query to find the sum of the different groups in the same column

    Hello

    I have a table as follows:



    visitors
    ------------------------------------------------------------------------------------------
    months of amt credit CustID
    --------------------------------------------------------------------------------------------
    001 C 2000-Jan-2012

    001D 5000 Feb 2012

    001C 3000 Mar-2012

    001C 3000-Apr-2012

    001D 7000-may-2012



    I have to write a single query to calculate the sum of the credit and the sum of the flow values separately.


    Thank you and best regards,
    SB2011

    Hello

    Select decode (credit,' it, sum (amt), sum (amt)) in the Group of customers to credit;

    Published by: 937440 on 24 February 2013 07:06

  • How do rotate on a date and see the sum of the value of another column

    Hello

    I searched through the forum and cannot find a query similar to my question feels so post this new thread.

    First of all, it is probably useful indicating that I am using Oracle 10 g.

    I have a table that is used to store the details of the booking (essentially a booking system) and I would use this data to display the details of the customers stay on one line.

    The table has the following columns:
    BOOKING_ID
    CUSTOMER_ID
    DATE_OF_ARRIVAL
    NUMBER_OF_NIGHTS
    NUMBER_OF_PEOPLE
    Some example records could be:

    BOOKING_ID    CUSTOMER_ID     DATE_OF_ARRIVAL    NUMBER_OF_NIGHTS   NUMBER_OF_PEOPLE
    --------------------------------------------------------------------------------------------
    1                    201      13-JAN-2010        5                   1
    2                    202      13-JAN-2010        3                   2  
    3                    202      13-JAN-2010        4                   1
    4                    203      15-JAN-2010        2                   3
    On this basis I would like to display the output so that I can show a sum of the NUMBER_OF_PEOPLE reserved to per customer per day, as such:
    CUSTOMER_ID     13-JAN   14-JAN   15-JAN   16-JAN   17-JAN   18-JAN   19-JAN 
    -----------------------------------------------------------------------------------------
    201                   1       1        1        1        1        0        0
    202                   3       3        3        1        0        0        0
    203                   0       0        3        3        0        0        0
    I watched analytical functions in the documentation and several books of Oracle that I have, but have so far struggled to find how to make the performance desired. Even using the excellent response to the previous post on the forum, I got Re: how to count the occurrence of a date in a range I was not able to get a feasible request.

    Any help or advice would be much appreciated.

    Kind regards
    Stu

    Published by: macmanxie on January 10, 2011 21:16

    Hello

    macmanxie wrote:
    ... The suggested approach goes only to return a number if the DATE_OF_ARRIVAL corresponds to the date in the CASE statement, however I have the added complexity of wanting to show a count of all the days that the customer is booked, for, by making use of the NUMBER_OF_NIGHTS. I tried to use some of the examples provided on morganslibrary.org, for example:

    sum( CASE WHEN  TRUNC (arrival_date) between '01/13/2011' and TRUNC (arrival_date+no_of_nights) THEN nvl(no_of_people,0) ELSE 0 END) AS jan_13
    

    but this does not produce the desired result.

    You check if arrival_date is between January 13 and arrival_date + no_of_nights (as if the arrival date could all be posterior to the arrival_date + no_of_nights).
    Are not really interested in whether or not January 13 ib between arrival_date and arrival_date + no_of_nights?

    NVL ( SUM ( CASE
                    WHEN  TO_DATE ( '01/13/2011'
                           , 'MM/DD/YYYY'
                         )          BETWEEN  TRUNC (arrival_date)
                             AND       TRUNC (arrival_date) + no_of_nights
                 THEN  no_of_people
             END
           )
        , 0
        )          AS jan_13
    

    Always format your code. It is important to format your code if you are the only who who will ever read but it is even more important if you are posting on a forum like this and ask other people to read.
    Not to compare the DATEs in the strings; explicitly use a conversion function, like TO_DATE, above, where necessary.
    Both
    SUM (NVL (x, 0)) and
    NVL (SUM (x), 0) get the same results, but the latter is more effective. If you have 1000 lines, the first way is calling NVL 1000 times, but the second way is calling only once.

    If your previous thread
    Re: How to count the occurrence of a date in a range
    Gets you the right data, but it has one row for each distinct combination of customer_id and date, then you can switch it to a form that contains a line by the customer and another column for each date.

    If you need help, post CREATE TABLE and INSERT statements for some examples of data and outcomes from these data. The post you are trying better to a request, including a subquery that gets no cross-the raw table dynamic results.
    There will be a fixed number of columns in the output swing? If this is not the case, how do you deal with that? Which of these options in the thread I posted above)
    Re: County report and the sum of the number of rows by multiple columns
    ) is best for your needs? Than others is acceptable?

  • JavaScript for the sum of a column cells

    Hi all -

    I have a table in expansion (lines can be added) and I am using the line of the column footer to calculate the average of the cells which do not have the value 0.

    Form Calc is usually great, but in this case, I need to divide the sum by the number of cells that are not zero and I don't know how to do this via form Calc.

    Successfully used javascript to identify the total number of occurrences and identify the number of instances that are zero, then the part of the denominator of the equation is fine. (Number of cases - number of zeros = denominator.)

    Now, it's just the numerator. There must be a loop, right?

    Is called table: table1

    Line is called: data

    cell is called: rated

    Any thoughts? Or more effective methods? Thank you very much.

    B

    Hello

    a solution in FormCalc could look this way:

    form1.#subform[0].table1.footer.sum::calculate - (FormCalc, client)
    var c = 0
    var s = 0
    for i = 0 upto (_data.count - 1) do
      if (data[i].eValue gt 0) then
      c = Sum(c, 1)
      s = Sum(s, data[i].eValue)
      endif
    endfor
    
    if (s gt 0 and c gt 0) then
      $ = Round(s / c)
    else
      $ = 0
    endif
    

    Put this scriot in the calculate of the cell of the footer line event.

Maybe you are looking for