SUM(column) produces incorrect amount

Hope someone can answer this:
5 tables -> a,b,c,d,e
a joins to b and c via one key, and c joins to d and d joins to e.
In the query:
SELECT count( DISTINCT ( a.k1 ) ) A,
count( DISTINCT ( b.k2 ) ) B,
count( DISTINCT ( c.k3 ) ) C,
sum(d.size) total_stuff
FROM tableA a , tableB b, tableC c, tableD d, tableE e
WHERE
a.k1 = b.k1
AND b.k1 = c.k1
AND c.k3 = d.k3
AND d.k4 = e.k4
AND ..<condition in table e>..
I always have a sum(d.size) that is inflated for each count(distinct(b.k2)) that is > 1. In other words, for each row returned, i need to divide the sum by the result of count(distinct(b.k2)).
Why would I need to do this ? And is there any good solution ?
thanks.

Rewrite the query so that a count(distinct d.x) will give the same result as a simple count(d.x). Then also the sum(d.x) will be correct.
One approach to do so is to use subqueries (IN, EXISTS) instead of joins. I would start with eliminating table b.

Similar Messages

  • How do you sum columns in same view

    I have a search component (drag and drop the viewCriteria) with a table.
    In the table is a column for an amount (number). I need to sum the amount and put it in the footer.
    I have done this many times with master/detail. Lots of info on that on the web as well. Really simple.
    In the view:
    So I create a transient attribute (sumAmount).
    I set the value to Expression and use one of the following (and several others that are not here).
    On the screen:
    drag SumAmount from the DC onto the footer. (OutputText no label)
    OK so far!?
    Run and query - (wishful thinking)
    Change the query and new totals appear (not that far yet).
    I have tried several permutations.
    adf.object.sum("Amount")
    sum("Amount")
    adf.object.ViewVO.getrowset.sum("Amount")
    All show absolutely nothing - I have the output text defined in the footer and the footer is displaying fine.
    The table also has some dates in the criteria - when I generate the rowImpl - the search panel is rendered useless due to the Date Domain vs Sql Date ( I know how to manage this)
    This has to be simple - just need to get a bit of help on it.
    I have tried to do this similar to the master/detail (but in this case - no detail). Still no value.
    I should be able to create a "formula" column without the use of java rowImpl.

    Finally - I have all the pieces - they are (were) as follows.
    1) create the View Object.
    2) add the summary column (transient) (be sure to get the data type correct (Number or BigDecimal)).
    3) create the view object implementation. (the Java tab in the view object - first box)
    4) create the view row implementation and expose the accessors. (the Java tab in the view object - second box).
    5) use Steve Muench's help to do the summation - it is a bit tricky and it has a depreciated call in it - but it works. (it is easy to modify to fit - just get the right attribute name for the sum & data type - I used Big Decimal)
    http://otn.oracle.com/products/jdev/tips/muench/recalctotalvo/RecalcTotalOfRowsInVO.zip (may have to look for the proper link - I found a lot of broken references)
    6) add a footer to the table in the search page and drag and output text box into it (all one step with drag and drop) - leave it empty.
    7) in the bindings page of the screen - add an attribute binding for the summary column from the Application Module.
    8) once the binding is made, go back to the output text box and use the inspector to create an expression and bind the value to "adf bindings" - data - and select the view-backing definition from the binding you just created.
    9) if you want to format this to right justified - surround with JSF HTML "panel grid - 1 column width=100% and style= text:align right - I usually do bold as well.
    10) sit back, relax and run - it should work.

  • Finder showing incorrect amount of free space

    After the recent Mountain Lion update, my Finder now shows an incorrect amount of free space.
    I have a 500GB hard drive, and I have about 150GB free.
    After the update, finder says I have 478.4 GB free?
    That looks like the total capacity, after you account for system software. I've done a PRAM and SCM reset, disk verification and repair, but still no joy.
    Any thoughts? Is it a bug in the update?

    Here is the answer....
    zchrykng
    Re: Hard drive available space shown incorrectly in finder Jan 12, 2012 7:35 PM (in response to ilari Korte)
    This is probably like the issue that I was having on my MacBook Pro. If you are using Time Machine on a laptop it stores the diffs in a file on your hard drive. This action can be disabled with the terminal command
    sudo tmutil disablelocal
    This turns the local Time Machine off. It is up to you if you want to do this, but Finder shows this space as unused since it can be overwritten when needed. It saved me over a hundred GBs of space.
    MacBook Pro, Mac OS X (10.7.2) 

  • Amount in Bar Code is incorrect;Amount in the line item can be used instead

    We have a problem in our Brazil company code.
    When we have a document with value higher than 5,000.00 BRL it is subject to Pis/cofins tax. In the Boleto (paper) document the amount is after tax deducted. But we see the full amount in the Vendor line item in SAP
    When the system reads the bar code and saves this code in the vendor line item during the document change we get a warning message no."8B797: Amount in Bar Code is incorrect;Amount in the line item can be used instead".
    And the amount in the Barcode line automatically adjusts itself to the line item amount which is the pre-tax amount (full amount).
    Example: Amount in the SAP Invoice doc is R$ 6,268.72   
                   Amount in Boleto (paper) R$ 5,977.22   (after deducting PIS/COFINS) - This amount appears in the bar code but once we press enter after the warning message it automatically adjusts to R$ 6,268.72 .
    We tried few notes like 784748 to apply but it says it is obsolete. We are on ECC 6.0 Release level 11.
    Regards.,
    Raj/

    answered through SAP note 784748

  • Bug in weblogic.rmic: produces incorrect IDL in factory decls.

    My EJB when producing IDL produces incorrect IDL: One of the outputs
    is java/net/URL.idl but when I try to compile it using Inprise
    visibroker
    4.0 for C++, I get the following parse error:
    /opt/inprise/vbrokercpp/bin/idl2cpp -no_servant -idl_strict
    -I/opt/inprise/vbrokercpp/idl -tie -namespace -no_pretty_print -Iidl
    -src_suffix cpp -root_dir cpp/java/lang idl/java/lang/ClassLoader.idl
    idl/java/net/URL.idl: 76:syntax error after )
    idl/java/net/URL.idl: 76:expected a[n]: ;
    idl/java/net/URL.idl: 76:instead of raises
    idl/java/net/URL.idl: 78:syntax error after )
    idl/java/net/URL.idl: 78:expected a[n]: ;
    idl/java/net/URL.idl: 78:instead of raises
    idl/java/net/URL.idl: 82:java::net::URLStreamHandler not found (expected
    type name)
    idl/java/net/URL.idl: 83:syntax error after )
    idl/java/net/URL.idl: 83:expected a[n]: ;
    idl/java/net/URL.idl: 83:instead of raises
    idl/java/net/URL.idl: 84:java::net::URLStreamHandler not found (expected
    type name)
    idl/java/net/URL.idl: 88:syntax error after )
    idl/java/net/URL.idl: 88:expected a[n]: ;
    idl/java/net/URL.idl: 88:instead of raises
    6 errors
    This is an error in the IDL: factory methods are trying to raise
    exceptions; however this is disallowed by the OMG IDL specification
    version 2.3:
    <init_dcl> ::= "factory" <identifier>"(" [ <init_param_decls> ]
    <init_param_decls> ::= <init_param_decl> { , <init_param_decl> }
    <init_param_decl> ::= <init_param_attribute> <param_type_spec>
    <simple_declarator>
    <init_param_attribute> ::= "in"
    As you can see, when using the keyword "factory" there is no "raises"
    clause allowed by the grammar.
    This is one of a few instances of the problem (this problem only
    occurred
    in one file but for several methods):
    factory
    create__CORBA_WStringValue__CORBA_WStringValue__CORBA_WStringValue( in
    ::CORBA::WStringValue arg0, in ::CORBA::WStringValue arg1, in
    ::CORBA::WStringValue arg2) raises (::java::net::MalformedURLEx);
    -Kim.

    the difference here is Thread-based security vs. Object-based security. WLS opts for the Thread-based model. this model was also
    backed up by the original revisions of the JAAS spec. it's just something to take into consideration when designing applications.
    .paul
    Marcel Stremming wrote:
    I have a SessionBean Method :
    public void contextTest() throws RemoteException {
    try {
    System.out.println("Principal 1: " + ctx.getCallerPrincipal());
    Properties h = new Properties();
    h.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
    h.put(Context.PROVIDER_URL, "t3://localhost:7001");
    h.put(Context.SECURITY_PRINCIPAL, "toto");
    h.put(Context.SECURITY_CREDENTIALS, "test");
    Context new_ctx = new InitialContext(h);
    System.out.println("Principal 2: " + ctx.getCallerPrincipal());
    } catch (Exception e) {e.printStackTrace(); }
    When principal "titi" invokes this Method it produces the following output:
    Principal 1: titi
    Principal 2: toto
    As You can see the Method just replaced the Caller Context's principal stored in the ctx field without even touching it. Since
    my Servlets run on the same JVM and use PassByReference calling this Method twice results in :
    Principal 1: titi
    Principal 2: toto
    Principal 1: toto
    Principal 2: toto
    I think this is a Bug because it makes it quiet difficult to open two Context's at the same time.
    I would like to read some opinions.

  • Incorrect total is being added up on registration form and submitted to PayPal as an incorrect amount

    We have an Adobe Central registration form for our event and when people total the cost and submit payment they are being billed an incorrect amount.  Pay Pal says this is an Adobe Forms issue.  Can you help?
    Thanks
    Susan

    Hi,
      Please provide the additional information that I requested via email.
    Thanks,
    Lucia

  • Sum Column Script

    This is not working; THANK YOU to anyone kind enough to point out what's missing.
       <field h="5.293mm" name="IncomeTotal" w="19.134mm" x="54.478mm" y="126.775mm">
                <ui>
                   <textEdit>
                      <border hand="right" presence="hidden">
                         <?templateDesigner StyleID aped0?></border>
                      <margin/>
                   </textEdit>
                </ui>
                <font size="11pt" typeface="Myriad Pro"/>
                <para vAlign="middle"/>
                <traversal>
                   <traverse ref="TextField4[3]"/>
                </traversal>
               <sum(IncomeTotal [Income1, Income2, Income3, Income4, Income5, Income6, Income7, Income8, Income9])>
             </field>

    Hi,
    First of all I would not recommend inputting script directly in the XML Source. If you go to the Design View you can open the Script Editor (5) from the Windows menu. I would recommend making it larger, so that you can see a few lines of script:
    You can see an example here for referencing objects in both JavaScript and FormCalc. This also includes an example for summing columns: http://assure.ly/kUP02y.
    Niall

  • Eclipselink producing incorrect sql - ORA-00918: column ambiguously defined

    We have a table with many columns .A1 .A2 .A3.... .A125 .N1 .N2 .N3... .N95 and with a simple jpql join it comes up with 2 columns that are ...AS N1150 and causing an ambiguous column error ...
    Does any one know of a valid workround or if this is a known bug. No problems were present in toplink, just eclipselink....
    it appears to be doing a count and suffixing the count to the column name to make sure the columns have unique id's - but failing:
    K1 -> K1 _1_
    N41 -> N41 _2_
    N11 -> N11 _50_
    ... then 100 columns later
    N1 -> N1 _150_
    the jpql is :
    @NamedQuery(name=NamedQueryNames.XREF_IMPORT_SELECT,
                   query="SELECT t FROM Tran t, Xref x "+
                   " WHERE t.key = x.a1 "+
                   " AND x.key.k1 = :partial "+
                   " AND x.key.k2 LIKE :partialX " +
                   " ORDER BY x.key.k2")
    Tran has fields k1,k2, a1, a2...a125, n1, n2...n95
    xref has k1,k2,a1,a2..a5, n1,n2,n3
    the sql eclipse link produces for the query is :
    SELECT *
    FROM
    (SELECT
    /*+ FIRSTROWS */
    a.*,
    ROWNUM rnum
    FROM
    (SELECT t1.K1 AS K11,
    t1.N41 AS N412,
    t1.N40 AS N403,
    t1.N45 AS N454,
    t1.N44 AS N445,
    t1.A120 AS A1206,
    t1.N43 AS N437,
    t1.A121 AS A1218,
    t1.N42 AS N429,
    etc
    t1.N25 AS N2547,
    t1.N10 AS N1048,
    t1.N12 AS N1249,
    t1.N11 AS N1150,
    t1.N17 AS N1751,
    a load more columns
    t1.A65 AS A65147,
    t1.A68 AS A68148,
    t1.A67 AS A67149,
    t1.N1 AS N1150,
    t1.A41 AS A41151,
    t1.N5 AS N5152,
    etc
    FROM COREXFA t0,
    CORETRA t1
    WHERE (((t1.K1 = t0.A1)
    AND (t0.K1 = ?))
    AND (t0.K2 LIKE ?))
    ORDER BY t0.K2 ASC
    ) a
    WHERE ROWNUM <= ?
    WHERE rnum > ?

    This issue is cause by the aliasing done because you are using firstResult/maxResult. I think there is already a bug logged for this issue, please vote for the bug.
    See,
    http://old.nabble.com/Duplicate-aliases-generated-for-columns-%281.1.3%29-td28039552.html
    Some workarounds would be,
    - avoid using firstResult/maxResult
    - rename the columns
    - use native SQL
    - use a cursor query instead of firstResult/maxResult
    James : http://www.eclipselink.org

  • Help Needed to Sum Column in Fixed Table

    I am new to LiveCycle.  I need to sum a column in a fixed table.  My rows are summing correctly.  I have tried every formula on the web both in FormCalc and Javascript.  I've cut and pasted script from Adobe templates and from forms on the web.  Nothing is working.  Each change produces a new set of errors.  The Hierarchy is:  (untitled Subform) (page 2), Table 2, Header Row {Header Row contains Year 1, Year 2...Year 5}, Row1 {Row1 contains Text Title, Cell2, Cell3, Cell4, Cell5, Cell6, (untitled Numeric Field) which is a calculated sum of Years 1-5}, Row2, Row3...Row7 are exactly the same.  I want to calculate the sum of each column in the footer row but I keep getting script errors.

    I am new to LiveCycle.  I need to sum a column in a fixed table.  My rows are summing correctly.  I have tried every formula on the web both in FormCalc and Javascript.  I've cut and pasted script from Adobe templates and from forms on the web.  Nothing is working.  Each change produces a new set of errors.  The Hierarchy is:  (untitled Subform) (page 2), Table 2, Header Row {Header Row contains Year 1, Year 2...Year 5}, Row1 {Row1 contains Text Title, Cell2, Cell3, Cell4, Cell5, Cell6, (untitled Numeric Field) which is a calculated sum of Years 1-5}, Row2, Row3...Row7 are exactly the same.  I want to calculate the sum of each column in the footer row but I keep getting script errors.

  • Addition of Key Figures in Query Produces incorrect Results

    Hi,
    I have a query with a globally defined structure of Restricted Key Figures. These are mainly G/L Account Balances from R/3.
    When I create a global Calculated Key Figure the sum is incorrect (ie does not match R/3) despite the fact that the individual restricted key figures match perfectly.
    The only inconsistency is one or 2 of the RKF's are + ve in R/3 but - ve in BW.
    Would really appreciate some help on this.
    Thanks a lot.

    Hi All,
    Thanks for your replies.
    Paul B - I tried your recommendation and it did not work. I only set the result to summation nothing else.
    Bjorn - I tried what you said but that didnt work either.
    Venkat - I thought about this but I have about 30 + Calculated Key Figs and over 100 Restricted Kfs and a fair amount have -ve signs. Do I have to do this for all ?
    Regards

  • Grands totals for % Columns coming incorrect in pivot view .

    Hello ,
    I have the below scenario . Iam trying to get the calculated grand total for % column . I tired several ways ...like report aggregates enabled in instanceconfig,tried creating cal colum using physical columns as well as logical columns in RPD , changing the aggregation rule. The row wise values (%) are coming correct but iam unable to get correct % grand total (36.8%) instead iam just getting the sum of the % total ( 83.3%) . I have tried the above options in my previous reports and those conditions work perfectly right but for this report they are not able to . kindly please let me know if anybody has a solution for this issue .
    Department ...USD CAD Variance (USD/CAD)*100
    XYZ 10 20 50%
    ABC 25 75 33.3%
    Total 35 95 36.8% ( 35/95)
    Thanks
    Karthik

    Just to cross check
    Do you have following tag in your instanceconfig file ? if its not there then you may encounter grand total incorrect calculations.
    <ReportAggregateEnabled>true</ReportAggregateEnabled>

  • Auto sum Column accumulated value in gridview

    The principle seems simple but I'm in trouble. Did anyone have an example or script to auto sum of a column in the gridview. Explain, I have a gridview with the columns:
    amount, unitary value, total value and accumulated value. I need the accumulated value column add the previous value
    to the current value. For example:
    quantity unitary_value total_value accumulated_value
    10 10,00 100,00 100,00
    20 50,00 1.000,00 1.100,00
    5 500,00 2.500,00 3.600,00
    Basically it would be up. The column value (accumulated value) takes the value of the previous line and adds to the current value.
    If you can help !!
    Thank you for your attention.
    Thank you for your attention.

    No you're right with the calculation of the first post, I got it wrong. Now check the below solution, you need to use RowDataBound event of the gridview to do the calculation and print in the cell:
    //This is just a method to fill the datatable with dummy data(you can ignore in your code)static DataTable GetTable()
    // Here we create a DataTable with four columns.
    DataTable table = new DataTable();
    table.Columns.Add("quantity", typeof(double));
    table.Columns.Add("unitary_value", typeof(double));
    table.Columns.Add("total_value", typeof(double));
    table.Columns.Add("accumulated_value", typeof(double));
    // Here we add five DataRows.
    table.Rows.Add(10, 10, 0, 0);
    table.Rows.Add(20, 50, 0, 0);
    table.Rows.Add(30, 40, 0, 0);
    return table;
    protected void Page_Load(object sender, EventArgs e)
    //Bind the gridview to the datatable
    GridView1.DataSource = GetTable();
    GridView1.DataBind();
    //Global var to keep accumulated value of each rowo
    double _accumulatedvalue = 0;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    if (e.Row.RowType == DataControlRowType.DataRow)
    //Create total value column by multiplying cells 1 and 2(maybe you don't need this)
    Double val = Convert.ToDouble(e.Row.Cells[0].Text) * Convert.ToDouble(e.Row.Cells[1].Text);
    e.Row.Cells[2].Text = val.ToString();
    //Accumualated value and fill the cell related (you can replace val below with Convert.ToDouble(e.Row.Cells[2].Text)
    _accumulatedvalue = _accumulatedvalue + val;
    e.Row.Cells[3].Text = _accumulatedvalue.ToString();
    Fouad Roumieh

  • Help w/Sum column

    The following query will return the last 10 records of a table where the record date falls within the first and last of the current month:
    <pre>
    SELECT *
    FROM (
    SELECT p_id, f2, amount, date1
    FROM mytable a
    WHERE a.date1
    BETWEEN TRUNC(SYSDATE,'MM') AND LAST_DAY(SYSDATE)
    ORDER BY a.date1 DESC, amount DESC
    WHERE rownum <= 10;
    </pre>
    Now I need to add a column to this query resultset that will have SUM(amount) for ALL the records in the current month (not just the last ten). The idea is that I can hide that last column from my application but still have the field available (total) to add as a footer.
    I tried (eliminating the semi-colon after the ten and then appending the following code to the query above:
    UNION
    SELECT '1','2,SUM(amount), SYSDATE
    FROM anothertable b
    WHERE b.date2
    BETWEEN TRUNC(SYSDATE,'MM') AND LAST_DAY(SYSDATE);
    ...but all that this does is adds a first record to the recordset with constants "1" and "2" to the first two fields, the desired total sum for the whole month, and the current date. However, I want that sum as another column (even though it may be there ten times), not at the top as another record.
    How can I do this?
    Thx!

    You could just add another subquery, like so:
    SELECT *
    FROM (
      SELECT p_id, f2, amount, date1,
          ( select sum(amount) from mytable
            where date1 between trunc(sysdate,'mm') and last_day(sysdate)) amount_total
      FROM mytable a
      WHERE a.date1
      BETWEEN TRUNC(SYSDATE,'MM') AND LAST_DAY(SYSDATE)
      ORDER BY a.date1 DESC, amount DESC
    WHERE rownum <= 10;

  • Unable to sum column in ALV

    I am using REUSE_ALV_GRID_DISPLAY to produce an ALV report. I want to display the sum row for some of the columns but am unable to do so for some. Some work others dont.
    They are all of type MBEW-SALK3 CURR 13. When I click on the Total button for some of the columns, the message pops up 'Desired operation cannot be performed for column'. Any idea why this must be happening. do_sum is set to 'X' and no_sum set to space.

    Hi I think you have missed following things while preparing Field Catalog.
    Below are the fields to be maintained for the currency fields in field catalog.
    cfieldname     type slis_fieldname, " field with currency unit
    ctabname       type slis_tabname, 
    Try with it.

  • Preview does not sum column data in PDF forms

    Preview is way better than Acrobat for most purposes, but it has some basic limitations that just make it hard to use. for example I have to use this form that asks you to enter $ in a table, however Preview does not sum the column, it just puts a "0" in. Why doesn't Preview add? Plus, this default behaviour makes it harder to paste in my own number as there is a zero in the way. At least it would be nice if it could just remove the 0 and leave me with an editble section. Is this just the product of a badly created PDF form or, as I suspect, a limitation of Preview?

    I'm having the exact problem. I have a fillable PDF form that has many checkboxes. Saving the pdf (doesn't matter whether it's 'Save', 'Save All', or 'Save As' under the File menu) will clear/reset the checkboxes in the file.
    Anyone know of a workaround for this? Or, is Apple fixing this soon? I really don't want to get Acrobat Pro 9 (well, I don't think it's compatible with Snow Leopard yet anyway)
    If you'd like a sample PDF file to try it out, let me know.
    Thanks.

Maybe you are looking for

  • Creating a genius bar reservation in apple store app?

    There's no way to create a new Genius Bar reservation with this app. Each time I tap the "Genius Bar" button on a store's reservation page, I end up on a page with two buttons: "Help" and "Call Apple" and a pop-up message that says "There is nothing

  • Tiger OSX 10.4 and Photoshop...what can i do?

    I recently purchaced adobe CS2 for my mac and everything works fine ... except for InDesign and Photoshop. I thought mac was a graphic based computer so i don't get why adobe doesn't work on the newest version of it's tiger... ? Is there anyway that

  • Organizing photos and keeing them organized when backing up

    Ok, I am kind of new to the iphoto thing, but I was wondering if there is a good way to keep the photos organized so they will stay organized when I back them up. I have created albums, but when I have to re-import the photos, they are not in any of

  • Cisco Prime 1.3 Trial version

    Hello, I could not find it by google. I have 2.2 but, Ionly have 8 GB of RAM, so I cannot deploy it. A download link (or a solution for 2.2 with 8GB RAM) would be awesome! THX!

  • Open a dwg(AUTO CAD )file in a jsp pageor servlet

    i am try to open a .dwg file in a web browser .i have given content type as a response.setContentType("image/x-dwg"); or response.setContentType("image/vnd-dwg"); users has the auto cad software please respond asap