Sum of columns in union query

hi, i am using oracle 10g database..
how to get the sum of column in union query ?
     select * from (select 100 records from dual), (select 50 available from dual)
union
select * from (select 200 records from dual), (select 150 available from dual)
display should be like
                 records         available
                  100               50
                  200               150
total            300               200thanks ...

Peter vd Zwan wrote:
try this:Grouping by records will not produce correct results:
SQL> with a as
  2  (
  3  select * from (select 100 records from dual), (select 50 available from dual)
  4  union
  5  select * from (select 100 records from dual), (select 100 available from dual)
  6  union
  7  select * from (select 200 records from dual), (select 150 available from dual)
  8  )
  9  select
10    case when grouping(records) = 0 then null else 'total' end tot
11    ,sum(records)   records
12    ,sum(available) available
13  from
14    a
15  group by
16  rollup (records)
17  ;
TOT      RECORDS  AVAILABLE
             200        150
             200        150
total        400        300
SQL> select  case grouping(rownum)
  2     when 1 then 'Total'
  3   end display,
  4          sum(records) records,
  5          sum(available) available
  6    from  (
  7            select * from (select 100 records from dual), (select 50 available from dual)
  8           union
  9            select * from (select 100 records from dual), (select 100 available from dual)
10           union
11            select * from (select 200 records from dual), (select 150 available from dual)
12          )
13    group by rollup(rownum)
14  /
DISPL    RECORDS  AVAILABLE
             100         50
             100        100
             200        150
Total        400        300
SQL> SY.

Similar Messages

  • How to get Average of a column in UNION query

    Hi All,
    I will try to explain the issue as much as I can and If you need clarification on any piece please let me know.
    So, I have a Union Query with two sets of Criteria.
    The first Criteria Brings the list of Buildings and a set of Measures for it. The second criteria does the same but with a different set of filters.
    No I use a UNION between these both criteria and present them in a Pivot view so that we only have one row per each building. The values in each of the criteria in the UNION query are Summed
    Ex:
    Building
    Metric 1
    Metric 2
    1
    20
    30
    1
    25
    35
    2
    40
    50
    2
    45
    55
    So as I show in the pivot the result is
    Building
    Metric 1
    Metric 2
    1
    45
    65
    2
    85
    105
    Now the issue is with the Grand Total.
    I want the Grand Total to be an Average of the Buildings. So for Metric 1 The Grand Total should be (45+85)/2 because we have two buildings so the answer should be 65.
    How can I get that.
    Bottom Line: Need an Average as the Grand Total when the Aggregation rule on the column is set to Sum.
    we use 11.1.6.10 version

    Hi VJ
    What you are asking is impossible in the pivot table itself as you are asking one part of the pivot table to aggregate via one method, and another to aggregate via another method, on the same column ..
    It can be done using a calculated item. For your example above you'd use the formula ( $1 + $2) / 2.
    .. But thats HIGHLY explicit, and would only work if you KNOW how many buildings will come back in the query.. EVERYTIME.
    Why not restructure the query to combine it into a single query using an combinations of filters with OR in between?

  • Including a SUM within a grouped UNION query

    Hi - I have inherited a (SSRS) report comprising two queries with a UNION. There is a requirement to add one extra column which SUMS a total for each resource per month. 
    Grouping additional columns results in the following error:
    Column 'dbo.MSP_EpmResource_UserView.ResourceName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
    Any help appreciated.

    Your issue is that the subselect in your from block now contains a SUM but the other columns are not part of aggregate functions etc.
    Even something simple like the following will give the same error:
    CREATE TABLE #ForumExample (ColumnOne VARCHAR(3),ColumnTwo VARCHAR(3), ColumnThree VARCHAR(3), ColumnToBeSummed INT)
    INSERT INTO #ForumExample
    VALUES ('A','C','E',1),('A','C','E',2),('B','D','F',3),('B','D','F',4)
    SELECT
     ColumnOne,
     SUM(ColumnToBeSummed)
    FROM #ForumExample FE
    DROP TABLE #ForumExample
    To solve this, don't SUM the value in the subselect, just get each value for each row and then in the main SELECT block SUM the column and make sure to group by the summed result (not the column itself).
    I havent had time to test this so I apologise if this doesn't work.

  • How to sum a column value using CAML Query?

    Hi All,
    I would like to sum the column value using CAML qeury. Actually in my list, I have two column "Projects Name" and "Number of Issues". Now need to get sum of "Number of Issues" column. How to achieve in CAML Query.
    Thanks in advance!

    Hi Sam,
    it looks like you can use your current view based agregation, otherwise it is not possible(
    http://msdn.microsoft.com/en-us/library/ms467521.aspx) and you need to work on custom bit on this requirement.
    use the below link and create a view element as described and see if that works for you
    Aggregations Element
    http://msdn.microsoft.com/en-us/library/ms468626%28v=office.12%29.aspx
    Another reference
    Query Element
    http://msdn.microsoft.com/en-us/library/ms471093.aspx
    Hope this helps!
    Ram - SharePoint Architect
    Blog - SharePointDeveloper.in
    Please vote or mark your question answered, if my reply helps you

  • How to Suppress Report Total When Using Sum on Columns & Break Formatting

    I need to know how to NOT show the report total line when using the sum functionality with a break in a report.
    I am summing two columns, a debit amount and credit amount. I am breaking on the first column which is the level of a hierarchical query. I want to see something like this:
    Parent Record xxxxxxxxxxxxxx
    Parent Sum $$ $$
    Child Record xxxxxxxxxxxxxx
    Child Record xxxxxxxxxxxxxx
    Child Sum $$ $$
    However, when I run the report, I also get a report total line under the child sum which is really meaningless for this report.
    I have also tried creating this report as an interactive report. When applying the sum on the two columns, I do get the sum totals on the break only - no report total - however, it is reversing the order of the hierarchical query results putting the child records first and the parent records second.
    Thanks in advance for your help.

    Hi, and welcome!
    I don't think that there's an easy way to "switch off" the Total line on a report. The nearest I could suggest would be to either hide the entire row or colour the text so that it's the same as the background - either way, the total is calculated but the user won't see it.
    If you put something like the following into your report region's Region Footer:
    <script type="text/javascript">
    var outertable = document.getElementById("#REGION_ID#");
    var innertable = outertable.getElementsByTagName("TABLE")[1];
    var rs = innertable.rows;
    var lastrow = rs[rs.length-1];
    if (lastrow.cells[0].innerHTML == '<b>TOTAL</b>')
    rs[rs.length - 1].style.display = "none";
    </script>Then, on your report's Report Attributes page, scroll down to the Break Formatting section and put TOTAL into the "Display this text when printing report sums" setting. Also, in the "Layout and Pagination" section, set "Enable Partial Page Refresh" to No.
    The above code is based on the report and region templates that I'm using here: [http://apex.oracle.com/pls/otn/f?p=267:147] (Theme 18, "Report Region" region template and "Standard" report template). Your report may use different templates, so the first two lines on the code may have to change. #REGION_ID# would be replaced with the region's ID value (which would be "R" followed by a long number). As long as you can identify the HTML tag that uses this ID value, you can then get to the actual table that contains the data as it would be a TABLE within that tag - the [1] above is the second table within the region. In some instances, you may have to use "region_#REGION_ID#" as the starting point.
    Andy

  • Sum fields in a sql query

    Hi,
    somebody knows how to sum two columns of a table as a result of an abap sql query. I know that is possible to do it in a native sql like
    select f.seatmax max, f.seatfree free, f.seatmax - f.seatfree seatoccu from flights
    Tks
    Roberto Falk

    Hi Roberto , 
      Here is a sample code which does some thing similar
    Data : v_LABST type LABST ,
           v_umlme type umlme.
    start-of-selection.
           select sum( labst ) sum( umlme )
             into (v_labst , v_umlme)
             from mard.
    write:/ v_labst , v_umlme.
    Regards
    Arun

  • ADD a column in a query

    Hi
    I want to add a column in my query.
    This column is the sum of the net value and the tax ..please how can I do this without refering to ABAP development..
    thanks in advance

    This is not an SD question and you might want to use Search (and include other forums) in the future.
    There is no ABAP needed for such basic calculations in queries. In SQ01, this can be done in the 'Select field' screen (it's the 3rd screen where you select which fields will be included in the query.
    First, assign short names to your Net Value and Tax fields. Go to the menu Edit -> Short Names -> Turn On/off. This should open another column to the right from the field names. Enter the names, say NET and TAX.
    Then create a new local field. Same menu, Edit -> Local field -> Create. Give the field some name (TOTAL), assign a type ('Same field as -> use Net field or whatever is suitable). Enter formula NET + TAX and save.

  • CFGRID - Sum of Column Values

    Hi,
    Is there a way to sum | total a column of numeric values in a
    cfgrid? I want to populate a cfinput text box with the number, and
    bind it so that as changes to numbers occur on the grid, the
    cfinput box changes.
    I've been able to do this by creating a function that goes
    and extracts the information via a database query. Running the
    query seems to add overhead to the screen response time.
    The variable could start as a value passed from a query. Say
    2000. When a field changes, it would take the original value,
    subtract out the original "row" value, then add in the new "row"
    value. Say a 2 is being replaced by a 3. Then you'd have 2000-2+3 =
    2001 which becomes the new "original" total value.
    Any thoughts would be appreciated.
    cfwild

    Hi Dan,
    Thanks for the feedback. The grid really works well for what
    I'm trying to do. I can filter the pages and make minor changes to
    the data quite quickly. When I add in the extra function (to sum
    the column) that goes out to the table to extract the data, it
    seems to take a performance hit on the "page".
    In looking at the code I've seen, it seems easy(?) to get to
    the new value of the column. Is there a decent way to get to the
    "old" value of the column, prior to an update? (or as you update)?
    cfwild

  • Sum datagrid column values

    I am looking for a way (action script code?) to sum datagrid
    column values.
    I am using Flex2 with Cold Fusion MX7.
    I populate a DataGrid by setting dataprovider to the result
    of a Coldfusion query.
    (this.masterList.dataProvider = event.result as
    ArrayCollection;)
    This all works fine.
    The masterList datagrid has debit, credit, and unitcost
    columns. I want to sum those columns individually, and display the
    results in text boxes in another panel.
    I could run a Coldfusion query to return the sums, but would
    like to do it on the client side with action script.
    I want to sum them everytime I update the datagrid, so need
    action code that I can put in the result function.
    I am new to ActionScript, and not sure how to loop through
    the array collection(and/or) dataprovider and sum the items.
    Any help would be appreciated.
    Thanks.

    Loop through your array..if the arrayCollection was named
    myArray;
    private sumFunction():Number{
    var sum:Number=0;
    for(var i:uint=0;i<myArray.lenght;i++){
    sum+=myArray
    .debitValue;
    return sum;

  • Aggregating a union query

    OBIEE 10.1.3.3: We have a number of HR turnover reports that require calculations that use a formula of: #txns / average headcount. We need to run these reports for whatever beginning/ending dates the users enter. And, of course they need to be sliced and diced by any number of dimensions. I came up with a couple of different schemes to do this but keep running into roadblocks. It seems that a union is my best bet. here's the latest one generated:
    SELECT saw_0, saw_1, saw_2, saw_3, saw_4, (saw_3 + saw_4)/2 saw_5,
    (saw_2 / (saw_3 + saw_4)/2)*100 saw_6
    FROM
    ((SELECT saw_0, saw_1, saw_2, saw_3, saw_4 FROM ... WHERE...)
    UNION
    (SELECT saw_0, saw_1, saw_2, saw_3, saw_4 FROM ... WHERE...)
    UNION
    (SELECT saw_0, saw_1, saw_2, saw_3, saw_4 FROM ... WHERE...)
    )) t1 ORDER BY saw_0, saw_1
    the first union select puts #txns in saw_2 and zeroes in saw_3 and saw_4
    the second union select puts 1st date headcount in saw_3 and zeroes in saw_2 and saw_4
    the third union select puts 2nd date headcount in saw_4, and zeroes in saw_2 and saw_3
    The saw_6 calc won't work because the overall query needs to be aggregated. Here's the problem: When I add sum() clauses to the main query, it blows up because of no group by clause, and if I go into Advanced and try to add the group by and hit set sql, Answers cuts off the query and tells me there's no group by, even though it properly places the saw_0,saw_1 fields in the group by box below. Seems like a bug in Answers, because when I take the SQL I altered and run it from the Admin SQL tool, it returns the result I wanted.
    Any ideas? If you got this far, thanks for reading all of this...
    Greg

    I am using very similar query with union all and sum () to get approval ratings between any given dates, but I did not explicitly specify groupby and it works. I am using 7.8.4.

  • APEX Interactive Report - sum multiple columns table1 X with table2 value

    I have a challenge in oracle apex, were i want to sum multiple columns to give 3 extra rows namely points, Score, %score. There are more columns but chose only few for now.
    Below is an example structure of my data:
    Town | Sector | Outside| Inside |Available|Price
    Roy-----Formal----0----------0----------1------0
    Kobus Formal--0 ---------0--------- 1------0
    Wika ---Formal----0----------0--------- 1------0
    Mevo----Formal----1----------1---------1------0
    Hoch----Formal----1----------1---------1-------1
    Points--------------2----------2----------5-------1
    Score-------------10---------10---------10------10
    %score-----------20---------20---------50------10
    Each column has a constant weighting (which serves as a factor and it can change depending on the areas) in this case the weighting for this areas are the ones in the first row for the sector Formal:
    Sector |Outside| Inside |Available|Price
    Formal----1----------1 ----------1-----1
    Informal--1----------0 ----------2-----1
    I tried using the aggregate sum function in apex but it wont work since i need the factor in the other table. Which is where my challenge started
    To compute the rows below the report:
    points = sum per column * weighting factor per column
    Score = sum of no of shops visited (in this case its 5) * weighting factor per column
    % score = points/Score * 100
    The report should display as described above. With the new computed rows below.
    I kindly ask anyone to assist me with this challenge as i tried searchin on the internet for solutions but havent come across any.
    Thanks a lot for your support in advance!!

    >
    Please update your forum profile with a real handle instead of "823433".
    I have a challenge in oracle apex, were i want to sum multiple columns to give 3 extra rows namely points, Score, %score. There are more columns but chose only few for now.
    Below is an example structure of my data: Use <tt>\...\</tt> tags as described in the FAQ when posting code and sample data and layouts. Please edit the OP and reformat the example using <tt>\...\</tt> tags so it's clear.
    Town | Sector | Outside| Inside |Available|Price
    Roy-----Formal----0----------0----------1------0
    Kobus --Formal----0 ---------0--------- 1------0
    Wika ---Formal----0----------0--------- 1------0
    Mevo----Formal----1----------1---------1------0
    Hoch----Formal----1----------1---------1-------1
    Points--------------2----------2----------5-------1
    Score-------------10---------10---------10------10
    %score-----------20---------20---------50------10Each column has a constant weighting (which serves as a factor and it can change depending on the areas) in this case the weighting for this areas are the ones in the first row for the sector Formal:
    Sector |Outside| Inside |Available|Price
    Formal----1----------1 ----------1-----1
    Informal--1----------0 ----------2-----1I tried using the aggregate sum function in apex but it wont work since i need the factor in the other table. Which is where my challenge started
    To compute the rows below the report:
    points = sum per column * weighting factor per column
    Score = sum of no of shops visited (in this case its 5) * weighting factor per column
    % score = points/Score * 100
    The report should display as described above. With the new computed rows below.
    I kindly ask anyone to assist me with this challenge as i tried searchin on the internet for solutions but havent come across any.How critical to the solution is using an interactive report? It would be much easier to do this in a standard report where you've complete control over the query SQL and the report structure.
    When you have a problem you'll get a faster, more effective response by including as much relevant information as possible upfront. This should include:
    <li>Full APEX version
    <li>Full DB/version/edition/host OS
    <li>Web server architecture (EPG, OHS or APEX listener/host OS)
    <li>Browser(s) and version(s) used
    <li>Theme
    <li>Template(s)
    <li>Region/item type(s) (making particular distinction as to whether a "report" is a standard report, an interactive report, or in fact an "updateable report" (i.e. a tabular form)
    With APEX we're also fortunate to have a great resource in apex.oracle.com where we can reproduce and share problems. Reproducing things there is the best way to troubleshoot most issues, especially those relating to layout and visual formatting. If you expect a detailed answer then it's appropriate for you to take on a significant part of the effort by getting as far as possible with an example of the problem on apex.oracle.com before asking for assistance with specific issues, which we can then see at first hand.

  • Trying to narrow down a UNIONed query

    I've compared 2 tables using MINUS. There should have been no difference. Since there was, I used UNION to display the corresponding rows between both tables. Now, in my result set, I have to search through many rows that don't have correspondents to find rows that do.
    Basically how do I narrow the UNION query down so that only the corresponding pair rows that have differences in their columns show up? I'm trying to use the primary key which is a combination of the first 5 columns. My query looks like this:
    select
    TRADE_DATE, ORDER_ROUTE_UID, ORDER_ENTRY_DATE, LEG_NBR, GROUP_SEQ_NBR,
    AFFL_FIRM_GROUP_ID, REC_CREAT_DATE
    from ors_firm_affl_hist@MSS_JOBS_HISTP01_LINK01.WORLD
    union
    select
    TRADE_DATE, ORDER_ROUTE_UID, ORDER_ENTRY_DATE, LEG_NBR, GROUP_SEQ_NBR,
    AFFL_FIRM_GROUP_ID, REC_CREAT_DATE
    from ors_firm_affl_hist;
    How can I use TRADE_DATE, ORDER_ROUTE_UID, ORDER_ENTRY_DATE, LEG_NBR, GROUP_SEQ_NBR in order to have the query display only the rows that have correspondents in the other table as opposed to rows that just aren't in either table?

    Not sure if this meets your requirements;
    SQL> with t1 as (
       select 'jon' first_name, 'smith' last_name, 'j' middle_init from dual union all
       select 'tom', 'a', 'a' from dual union all
       select 'bob', 's', 's' from dual union all
       select 'Stan', 'm', 'l' from dual union all
       select 'Kyle', 'b', 'r' from dual union all
       select 'Kenny', 'm', 'r' from dual union all
       select 'Eric', 'c', 'c' from dual),
         t2 as (
       select 'jon' first_name, 'smith' last_name, 'p' middle_init from dual union all
       select 'tom', 'a', 'l' from dual union all
       select 'bob', 's', 'j' from dual union all
       select 'Stan', 'm', 'l' from dual union all
       select 'Kyle', 'b', 'r' from dual union all
       select 'Kenny', 'm', 'r' from dual union all
       select 'Eric', 'c', 'c' from dual)
       select 'T1' source, first_name, last_name, middle_init from t1
       minus
       select 'T1' source, first_name, last_name, middle_init from t2
    union all
       select 'T2' source, first_name, last_name, middle_init from t2
       minus
       select 'T2' source, first_name, last_name, middle_init from t1
    order by 2,3,1
    SO FIRST LAST_ M
    T1 bob   s     s
    T2 bob   s     j
    T1 jon   smith j
    T2 jon   smith p
    T1 tom   a     a
    T2 tom   a     l
    6 rows selected.

  • How to sum the column in a table seperated by sign.

    How to sum the column in a table separate by sign.
    For Example:
    A B
    10 MOHAN
    -15 KUMAR
    -25 MARCH
    50 MAY

    SELECT  SUM(CASE SIGN(A) WHEN 1 THEN A ELSE NULL END) SUM_POSTIIVE,
            SUM(CASE SIGN(A) WHEN -1 THEN A ELSE NULL END) SUM_NEGATIIVE
      FROM  tbl
    /SY.

  • Multiple Key figure in a single column of a query

    Hi,
    Is it possible to use muliple key figure like Amount and Qty field together in a column of a query?
    Please advise,
    Best Regards,
    UR

    Hi,
    You will be able to do it with the help of cell definitions.
    Say,you have a structure in Rows :
    A
    B
    For A ..in corresponding column cell,use cell definition with KF1
    For B.....in corresponding column cell,use cell definition with KF2
    this way,you will be able to see both in one column
    I m not sure how much it is relavant to your requirement.But this is one way of gettin it

  • Comment column in a query

    Hello,
    In a BW query, I need to add a column of text comments (for example, the description of a calculation, the unit used, ...). These texts are static, the queries will only be used as static reports (download scheduler), in excel and web, so we can not use any VB script.
    Is it a way to add some text in a cell of a column, as in the following example (columns 2 and 3) ?
    KF1    |    Comment for KF1    |    Euros    |    12
    KF2    |    Comment for KF2    |    %          |    47
    Thanks in advance
    Michaë

    Hi guys,
    finally how you fix this problem?, I need to show a comment in a query column and i don't know if this is posible ¿?, I have a query inside of a wad and I want to show a comment in the columns  of the query with the formula details.
    Please let me know if you this is possible.
    Thanks!, Kinds Regards

Maybe you are looking for

  • QM_move stock to block stock through Q2 notification type

    Dear QM Experts, u2022 I am creating quality notification type Q2 through QM01 u2022 After doing necessary defect entry I want to post the defective material to block stock. u2022 For this I am using action box transfer posting unrestricted to block.

  • How do I make CS4 not blur frames together when I slow down footage.

    I'm trying to get an effect similar to the oppening credits of Reservior Dogs, but whenever I slow down video, Premiere makes it look all ultra-smooth, which would be nice in most cases but in this one I want to just leave the frames as they are and

  • Inapp purchases implementation

    Hi Team, I need transaction more then $1000/- from in-app purchase on my application for just upgrading some account level of user's. But unfortunately i am not able to create products for price more than $999.99/-  according to Price Tier. What will

  • No Way To Crop To 2.35:1

    Suppose you wanted to crop a photo in Aperture to an exact aspect ratio, such as 2.35:1, there's no way to do it, is there? The crop tool only allows 2 digits per width and height. So, you can't type in 2.35 to 1 or even 235 to 100. Isn't that a bit

  • Importing 2 icloud photo streams into iPhoto

    Just as the title states.. My wife and I just started our own seperate iCloud accounts and now it seems like we can't combine them in iPhoto.  Before we used one account and pictures were seamlessly across all devices, and now since iOS 8 and continu