SUM without Group by

Hi,
I have a table like this..
Type      Amount      ID      Num      ActId
Primary 256.32      12345      01      7899
None     125.21      12345      01      7900
None     456.87      12345      01      7901
Primary 1258.45     98745      04      7902
Primary 468.11      45565      06      7903
None     1258.45     45565      06      7904
None      200.00      85598      09      7905I want to sum Amounts based on ID and Type. I DON'T want to use GROUP BY.. I want SUM (Amount) OVER (PARTITION BY ..
Result:
Type      Amount      ID      Num
Primary 838.4      12345      01           -- Sum of First 3 rows
Primary 1258.45     98745      04 -- display 4th row directly becuase its primary
Primary 1726.56     45565      06           -- Sum of 5th and 6th rowsthanks

Not sure why you don't want to use group by, but...
SQL> WITH t AS (SELECT 'Primary' type, 256.32 amount, 12345 id, '01' num, 7899 actid FROM dual UNION ALL
  2             SELECT 'None', 125.21, 12345, '01', 7900 FROM dual UNION ALL
  3             SELECT 'None', 456.87, 12345, '01', 7901 FROM dual UNION ALL
  4             SELECT 'Primary', 1258.45, 98745, '04', 7902 FROM dual UNION ALL
  5             SELECT 'Primary', 468.11, 45565, '06', 7903 FROM dual UNION ALL
  6             SELECT 'None', 1258.45, 45565, '06', 7904 FROM dual UNION ALL
  7             SELECT 'None', 200.00, 85598,'09', 7905 FROM dual)
  8  SELECT type, amount, id, num
  9  FROM (SELECT type, id, num,
10               SUM(amount) OVER (PARTITION BY id) amount
11        FROM t)
12  WHERE type = 'Primary'
13  ORDER BY num;
TYPE        AMOUNT         ID NU
Primary      838.4      12345 01
Primary    1258.45      98745 04
Primary    1726.56      45565 06John

Similar Messages

  • SUM WITHOUT GROUP CLAUSE

    I want to sum the total of Positive Balances and Negative Balances in table. My DDL is as under:-
    CREATE TABLE LUQMAN
    (ID NUMBER(1),
    AMOUNT NUMBER(5));
    INSERT INTO LUQMAN VALUES(1,20000);
    INSERT INTO LUQMAN VALUES(1,-2000);
    INSERT INTO LUQMAN VALUES(1,5000);
    INSERT INTO LUQMAN VALUES(1,20000);
    INSERT INTO LUQMAN VALUES(1,2300);
    INSERT INTO LUQMAN VALUES(2,-50000);
    INSERT INTO LUQMAN VALUES(2,-2000);
    INSERT INTO LUQMAN VALUES(2,5000);
    INSERT INTO LUQMAN VALUES(2,20000);
    INSERT INTO LUQMAN VALUES(2,2300);
    INSERT INTO LUQMAN VALUES(3,20000);
    INSERT INTO LUQMAN VALUES(3,-2000);
    INSERT INTO LUQMAN VALUES(3,5000);
    INSERT INTO LUQMAN VALUES(3,20000);
    INSERT INTO LUQMAN VALUES(3,2300);
    INSERT INTO LUQMAN VALUES(4,-50000);
    INSERT INTO LUQMAN VALUES(4,-2000);
    INSERT INTO LUQMAN VALUES(4,5000);
    INSERT INTO LUQMAN VALUES(4,20000);
    INSERT INTO LUQMAN VALUES(4,2300);
    COMMIT;
    The query should return One Row Answer as under:-
    POSITIVE NEGATIVE
    90600 -47100
    I tried following but could not got the correct answer.
    SELECT CASE WHEN ID IN (1,2,3,4)
    AND SUM(AMOUNT)>0 THEN SUM(AMOUNT) ELSE 0 END POSITIVE,
    CASE WHEN ID IN (1,2,3,4)
    AND SUM(AMOUNT)<0 THEN SUM(AMOUNT) ELSE 0 END NEGATIVE
    FROM LUQMAN;
    Any Idea please, how to return above One Single Row ? I want one cumulative balance, not by ID Group.
    Thanks and Regards,
    Luqman

    SQL> ed
    Wrote file afiedt.buf
      1  select sum(positive),sum(negative) from
      2  (
      3  select case when sign(amount)=1 then amount end positive,
      4  case when sign(amount)=-1 then amount end negative from LUQMAN
      5* )
    SQL> /
    SUM(POSITIVE) SUM(NEGATIVE)
           149200       -108000
    SQL> SELECT * FROM LUQMAN
      2  /
            ID     AMOUNT
             1      20000
             1      -2000
             1       5000
             1      20000
             1       2300
             2     -50000
             2      -2000
             2       5000
             2      20000
             2       2300
             3      20000
            ID     AMOUNT
             3      -2000
             3       5000
             3      20000
             3       2300
             4     -50000
             4      -2000
             4       5000
             4      20000
             4       2300
    20 rows selected.
    luqman123 wrote:Hi,
    Your query returning wrong total.Can you check your inserts again ...
    HTH

  • Filter by Sum without Grouping

    i have a resultset that i generate from a query that Looks like this:
      Select Employee, Month,
    (select case
    when Status = '---'
    then 0 Else
    1 end) as PlaningValue     
      From   PlanningTable PT
      Where  Month >=
    @From Month and Month
    <= @ToMonth
    The Result of this Looks something like this:
    |Employee| Month   
    | PlaningValue |
    |George    |2014-01 
    |                
    1 |
    |George    |
    2014-02 |                
    1 |
    |George    |
    2014-03 |                 0
    |
    |Andrew    |
    2014-01 |               
    0 |
    |Andrew    |
    2014-02 |               
    1 |
    |Andrew    |
    2014-03 |               
    0 |
    |Howard    |
    2014-01 |               
    1 |
    |Howard    |
    2014-02 |               
    1 |
    |Howard    |
    2014-03 |                1
    |
    Now what i want is the following:
    Filter out Employee's who, over the three month period, have a total planing Value of 3, in the example above, Howard would be filtered out.
    Is there a way to do this nicely or is it all just impossible to even thin ?
    (Remark: Since i am going to use the Query on Reporting Services, i can't use the OVER function)
    Thank you all for your help

    Jingyang's answer is a top choice, assuming SQL Server 2005 or greater (you didn't say what version, everybody should!).  I wrote up a version doing the same thing before I noticed Jinyang's answer already was here.  The last item in the list is
    a derived query version, same net effect as using the WITH statement.
    Create_Demo_table:
    Declare @Demo Table (employee varchar(99), month varchar(77), status int)
    Insert @Demo
    Select 'George', '2014-01 ', 1
    UNION ALL Select 'George', '2014-02', 1
    UNION ALL Select 'George', '2014-03', 0
    UNION ALL Select 'Andrew', '2014-01', 0
    UNION ALL Select 'Andrew', '2014-02', 1
    UNION ALL Select 'Andrew', '2014-03', 0
    UNION ALL Select 'Howard', '2014-01', 1
    UNION ALL Select 'Howard', '2014-02', 1
    UNION ALL Select 'Howard', '2014-03', 1
    With_Stmt:
    ;With X as
    Select *
    , sum(status) over(partition by employee) as sumStat
    from @Demo
    where month between '2014-01' and '2014-03'
    Select * from X where SumStat < 3
    Derived_query:
    Select * from
    Select *
    , sum(status) over(partition by employee) as sumStat
    from @Demo
    where month between '2014-01' and '2014-03'
    ) Derived1
    where Sumstat < 3

  • Nested Group Function without Group By Problem

    Hey everyone,
    I have 3 tables as below:
    TABLES
    ITEM (Item_no, Item_price, desc)
    DeliveryItem (delivery_no, item_no, quantity)
    Delivery (delivery_no, delivery_date)
    SELECT desc, MAX(SUM(quantity)) FROM DeliveryItem, Item, Delivery WHERE Item.item_no = DeliveryItem.item_no AND Delivery.delivery_no = deliveryitem.delivery_no;
    And I'm trying to output description of most delivered item but I got an error like SQL Error: ORA-00978: nested group function without GROUP BY. Could you help me to fix my code?
    Thanx

    Hi,
    DESC is not a good column name; you could get errors if the parser thinks it means DESCending. I used DESCRIPTION instead, below.
    I think the best way is to do the SUM in a sub-query, lkike this:
    WITH     got_r_num     AS
         SELECT       item_no
         ,       SUM (quantity)     AS total_quantity
         ,       RANK () OVER (ORDER BY  SUM (quantity) DESC)     AS r_num
         FROM       deliveryitem
         GROUP BY  item_no
    SELECT     i.description
    ,     r.total_quantity
    FROM     got_r_num     r
    JOIN     item          i     ON     r.item_no     = i.item_no
    WHERE     r.r_num     = 1
    ;If you want to do it without a sub-query:
    SELECT       MIN (i.description) KEEP (DENSE_RANK LAST ORDER BY SUM (di.quantity)
                        AS description
    ,       MAX (SUM (quantity))     AS total_quantity
    FROM       deliveryitem     di
    JOIN       item          i     ON     d1.item_no     = i.tiem_no
    GROUP BY  i.description
    ;If you do nested aggegate functions, then every column in the SELECT clause must be an aggregate applied to either
    (a) another aggregate, or
    (b) one of the GROUP BY expressions.
    That's why you got the ORA-00937 error.
    This second approach will only display one row of output, so If there is a tie for the item with the greatest total_quantity, only one description will be shown. The RANK method will show all items that had the highest total_quantity.
    It looks like the delivery table plays no role in this problem, but it there's some reason for including it, you can join it tpo either query above.
    Of course, unless you post test copies of your tables (CREATE TABLE and INSERT statements) I cn't test anything.
    Edited by: Frank Kulash on Nov 6, 2010 10:57 AM

  • How to store the value of sum of group in Crystal Report at the runtime!

    Hello all,
    I creates a Formula Field that hold the value of Sum of Group in Crystal Report. I would like to know how to store it in a variable and pass it to store procedure. Is it an option in Crystal report to do it. I knew that Crystal Report can cache the report for sharing. My detailed issue as following:
    - Created a Formula Field named TOTAL AMOUNT that calculated the complex expression. This TOTAL AMOUNT is dynamic based on group and variables.
    - I would like to store that value from TOTAL AMOUNT and pass it to the stored procedure parameter IN.
    Any helps are much appreciated. Thanks.

    I doubt that this is possible since it would only calculate this value once the report has data.  This sounds more like a report design question that should be asked over [here|SAP Crystal Reports;

  • Nested group function without group xmlagg

    I am getting nested group function without group by xmlagg when using the xmlagg function inside another xmlagg function. Find the table structure and sample data here,
    CREATE TABLE "TEST_TABLE"
       ("KEY" NUMBER(20,0),
        "NAME" VARCHAR2(50 ),
        "DESCRIPTION" VARCHAR2(100 )
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (1,'sam','desc1');
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (2,'max','desc2');
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (3,'peter',null);
       Insert into TEST_TABLE (KEY,NAME,DESCRIPTION) values (4,'andrew',null);
    select
            XMLSerialize(document
            xmlelement("root",
             xmlagg(
               xmlelement("emp"          
               , xmlforest(Key as "ID")          
               , xmlforest(name as "ename")
               , xmlelement("Descriptions", 
               xmlagg(
                  xmlforest(description as "Desc")
           ) as clob indent
           ) as t   
          from test_table;Then i removed the xmlagg function from the above select query and used xmlelement instead
      select
            XMLSerialize(document
            xmlelement("root",
             xmlagg(
               xmlelement("emp"          
               , xmlforest(Key as "ID")          
               , xmlforest(name as "ename")
               , xmlelement("Descriptions",            
                  xmlforest(description as "Desc")
           ) as clob indent
           ) as t   
          from test_table;This is working fine, but xml created with empty elements for Descriptions element for key 3 and 4 which has null values. I need don't need Descriptions element in the xml when it has null value. Please help me to resolve this.

    You can do it with a correlated subquery :
    SQL> select xmlserialize(document
      2           xmlelement("root",
      3             xmlagg(
      4               xmlelement("emp"
      5               , xmlforest(
      6                   t.key as "ID"
      7                 , t.name as "ename"
      8                 , (
      9                     select xmlagg(
    10                              xmlelement("Desc", d.description)
    11                              order by d.description -- if necessary
    12                            )
    13                     from test_desc d
    14                     where d.key = t.key
    15                   ) as "Descriptions"
    16                 )
    17               )
    18             )
    19           ) as clob indent
    20         )
    21  from test_table t;
    XMLSERIALIZE(DOCUMENTXMLELEMEN
    <root>
      <emp>
        <ID>1</ID>
        <ename>sam</ename>
        <Descriptions>
          <Desc>desc1_1</Desc>
          <Desc>desc1_2</Desc>
          <Desc>desc1_3</Desc>
        </Descriptions>
      </emp>
      <emp>
        <ID>2</ID>
        <ename>max</ename>
        <Descriptions>
          <Desc>desc2_1</Desc>
          <Desc>desc2_2</Desc>
          <Desc>desc2_3</Desc>
        </Descriptions>
      </emp>
      <emp>
        <ID>3</ID>
        <ename>peter</ename>
      </emp>
      <emp>
        <ID>4</ID>
        <ename>andrew</ename>
      </emp>
    </root>
    Or an OUTER JOIN + GROUP-BY :
    select xmlserialize(document
             xmlelement("root",
               xmlagg(
                 xmlelement("emp"          
                 , xmlforest(
                     t.key as "ID"
                   , t.name as "ename"
                   , xmlagg(
                       xmlforest(d.description as "Desc")
                       order by d.description -- if necessary
                     ) as "Descriptions"
             ) as clob indent
    from test_table t
         left outer join test_desc d on d.key = t.key
    group by t.key
           , t.name
    ;Edited by: odie_63 on 11 juil. 2012 14:54 - added 2nd option

  • Sum Current Group With filter

    Dear All,
    I have problem to sum data using filter/conditon
    i want to sum data like this:
    No Budget SM GG
    1.2 *400 200*
    1.2.1 100 100
    1.2.2 200 200
    1.2.3 300 300
    1.3 400 400
    and using
    <?sum(current-group()/TotalPrice[.!='' and PaymentAllocation='GG'])?>
    but show no data
    i also tried
    <?xdoxslt:set_variable($_XDOCTX, ’INITGG’, xdoxslt:get_variable($_XDOCTX, ’INITGG’)
    +xdoxslt:ifelse(PaymentAllocation='GG',xdoxslt:ifelse(TotalPrice[.!=''],TotalPrice,0),0))?>
    but nothing happen, seem the code didn't recognized the group(have 2 group inside)
    Please help me
    Thank so much
    Regards
    Cecilia

    You can use <?sum(current-group()/TotalPrice[.!='' and ../PaymentAllocation='GG'])?>

  • Reset Group Sum at group change .... Urgent......

    Hi,
    I ve 4 groups in my report as a,b,c,d . and the structure is
    a
    |--> b
    |-> c
    |-> d
    ie. group d is nested in c, c is nested in b , b is nested in a.
    I want sum of group d . But at the same time when any of groups a,b,c changes , sum should be reset .
    Plz let me know how to reset sum on changing any of the groups a,b,c in same hierarchy.

    Hi
    Try to set it in the properties of the sum.
    Ott Karesz
    http://www.trendo-kft.hu

  • Eliminating NULLs for SUM(current-group)

    I face the following problem:
    I have some NULL values in my data which I elimnated by a <?xdofx:decode(FIELD,'',0,FIELD)?>
    add. I have defined a summary field with <?sum (current-group()/FIELD)?> that results in "NaN" because of the NULLs.
    But decode doesn't work in the sum(c... ) !?
    Any help is appreciated.
    Dirk

    Hi,
    I didn't know about the to_number, that's useful to know.
    It get's a little ugly in your template but you can work around have the sum before the for-each. The answer is to have a for-each purely to create the sum. I've had to do it for a couple of templates.
    I usually put the code in a template to make it easier to read and the not put too much code in to a cell in a table. Try the following:
    <?template:t_sumdata?>
    <?for-each:xxx?>
    <?if:ELEMENT!=''?>
    add to variable
    <?end if?>
    <?end for-each?>
    <?end template?>
    The above code can go anywhere in your template, I normally put them at the end. To reference this just put
    <?call:t_sumdata?><?get variable value?>
    where you want the total to appear.
    Thanks
    Paul

  • Sum without using 2 selects

    How can I get this result without using 2 queries to sum buys and sells?
    BANK  TOTAL_SHARES
    BANK1           30
    BANK2           25
    BANK4           20
    BANK5           20
    BANK3           15
    Script to test
    create table test (BUYER varchar2(5), SELLER varchar2(5), shares numeric(10));
    insert into test values ('BANK1','BANK1',10);
    insert into test values ('BANK1','BANK2',10);
    insert into test values ('BANK3','BANK2',15);
    insert into test values ('BANK4','BANK5',20);
    commit;
    select bank, sum(shares) total_shares from
    select buyer bank, sum(shares) shares from test group by buyer
    union
    select seller bank, sum(shares) shares from test group by seller
    group by bank
    order by total_shares desc, bank;

    So .. you have 2 records for BANK1:
    insert into test values ('BANK1','BANK1',10);
    insert into test values ('BANK1','BANK2',10);
    You want to add that first 10 , twice .. and the 2nd 10 once?
    BANK1           30
    So you want to double add some of those?

  • Sum and group by using CAML query

    Is there any way to get the SUM of values with group by ID using CAML query?
    I have a custom list, in that I have ID and Value columns as below
          ID         Value1      Value2
          1             10             4
          2              5              3
          1             15             2
          3             20             1
    I want to get result:
         ID          Value1        Value2
         1             25                6
         2             5                  3
         3             20                1
    I used CAML query:
    <View>
    <Query>
    <Where>
    <IsNotNull>
    <FieldRef Name="ID" />
    </IsNotNull>
    </Where>
    <GroupBy Collapse="FALSE">
    <FieldRef Name="ID" />
    </GroupBy>
    </Query>
    <ViewFields>
    </ViewFields>
    <Aggregations Value="On">
    <FieldRef Name="Value1" Type="SUM" />
    <FieldRef Name="Value2" Type="SUM" />
    </Aggregations>
    </View>
    But
    this query returns all the records
    that satisfy the condition <Where>.
    I
    do not correctly?

    You need to work with current view based aggregation. Please check below threads for your reference.
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/dda5735a-fecf-403f-9495-1b63617d2fbf/question-on-a-caml-query?forum=sharepointdevelopmentlegacy
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/24e88d6a-ee15-4d81-a5fe-504c7bd14e46/how-to-sum-a-column-value-using-caml-query?forum=sharepointdevelopment
    Hope this helps.
    My Blog- http://www.sharepoint-journey.com|
    If a post answers your question, please click Mark As Answer on that post and Vote as Helpful
    I've seen these
    issues and articles and do them, but
    does not work. I use object mozhel
    Sharepoint (javascript).

  • Is it possible to sum across groups

    Dear all,
    I want to define a template for AP cash requirement report to sum amount to be paid by vendor. The XML tree structure is to first group by Due Date and then group by Vendor. Therefore, the invoices to be paid can be under different Due Date groups. My question is, is it possible to sum by Vendor name regardless which Due Date group (the parent group) it belongs to?
    Thanks!
    Sandy

    Hi,
    Seems the XML tree is not allowed to be posted here. Please find it in the link below. G_Date is a parent group of G_Vendor. I want to be able to sum by vendor regardless of the which G_Date group it is belonged to. Please advise. Thanks!
    https://communities.oracle.com/portal/server.pt/community/view_discussion_topic/216?threadid=80778&aggregatorResults=T80778T79511T79424T78340T78009T76654T70958T47945T46834T45020&returnUrl=https://communities.oracle.com/portal/server.pt/community/discussions/209#80778

  • Select Empno,name,sum()..group by empno only  Is this possible?

    select empno,name,sum(sal) from emptable where year=' ' groub by empno order by empno.
    this query getting error because i didn't include empname in group by.
    But if i include this name, my sum is not correct.
    so i want to empno,name but i don't want to include name in group by. Is this possible?
    My oracle verion is 8.
    IS any other solution to solve this problem?
    Thanks in advance.

    i want to empno,name but i don't want to include name in group by. Is this possible?<br>
    <br>
    No. It isn't.
    <br>
    select empno,name,sum(sal) over (partition by empno) <br>
    from emptable
    <br>where year=' '
    <br>
    -- <s>groub by empno</s>
    <br>
    order by empno;

  • Find Sum of grouped events by date

    I'm using Report Builder 10.50.2500.0
    I've been trying to do this for awhile and have run out of ideas to try.  I think it's a simple solution but I can't figure it out.
    I have a database that is used for events. A booking can have several different events associated with it, even on the same day at different times.  The events can be classified as breakfast, lunch or dinner events.
    The report is grouped by type of event, then by event date (not datetime, the overall date), then grouped by booking.
    Basically, I need the sum the total attendance of each breakfast, lunch, and dinner event by date and by booking.
    For breakfast events I have this code on the Event Classification group row:
    =iif(Fields!EventClassification.Value = "Breakfast",SUM(Fields!CurrentAttendance.Value),0) and the same for lunch and dinner. This works except when when there is more than one event per day.
    For example, on 6/11/13 there is one lunch event and one dinner event.  The report shows
    Date
    EventName
    Breakfast
    Lunch
    Dinner
    6/11/13
    EventName
    0
    50
    0
    6/11/13
    EventName
    0
    0
    50
    When what I want is:
    Date
    EventName
    Breakfast
    Lunch
    Dinner
    6/11/13
    EventName
    0
    50
    50
    Any ideas?  I've tried using group variables and passing to a report variable and acting on that but that didn't work out properly.

    Hi Jmelinda,
    In order to achieve your requirement, we can refer to the following steps:
    In the Row Groups pane, right-click the Details group to add a parent group grouped by Date field.
    Right-click the Date group to add a parent group grouped by Date field.
    Right-click the Date group to add a total row after the group.
    Delete the second and third columns with “Delete columns only” option for Date field.
    Type the expression below to the total row for Breakfast column, and the same for lunch and dinner:
    =sum(iif(Fields!EventClassification.Value = "Breakfast", Fields!CurrentAttendance.Value, 0))
    Set the visibility of second row to Hide.
    The following screenshot is for your reference:
    If there are any other questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Aggregate functions without group by clause

    hi friends,
    i was asked an interesting question by my friend. The question is...
    There is a DEPT table which has dept_no and dept_name. There is an EMP table which has emp_no, emp_name and dept_no.
    My requirement is to get the the dept_no, dept_name and the no. of employees in that department. This should be done without using a group by clause.
    Can anyone of you help me to get a solution for this?

    select distinct emp.deptno,dname
    ,count(*) over(partition by emp.deptno)
    from emp
    ,dept
    where emp.deptno=dept.deptno;
    10     ACCOUNTING     3
    20     RESEARCH     5
    30     SALES     6

Maybe you are looking for

  • BPM: ICWebClient Monitoring

    Hi Colleagues, I'm searching for information on ICWebClient performance monitoring. Anyone can tell me what tools we could use? Is there any "monitoring alert" in Solman BPM? I'm posting a similar thread in CRM Interaction Center forum. Regards, Rena

  • CALL TRANSACTION LM03

    An External Program does a simple CALL TRANSACTION 'LM03'. Passing in the Transfer Order Number. The desired result is to return to the calling program, instead it returns to the RF Menu. It appears the call stack in the LMOB will prevent us from ret

  • Problems uploading music to Ze

    Hi there everyone,?Yesterday i bought myself a new Creative zen V to replace my old zen micro, which got broken...when i tried to upload music to it the first time it worked perfectly fine.but halfway the uploading process, it stopped uploading.so I

  • My Photoshop Elements 6.0 does not work with Windows 8

    I recently updated my Notebook from Vista to Windows 8. Now I do have to install al programms again, but concerning PSE 6, there is a catastrophically failure with the licencing subsystem AMT. Does anybody know how I can use this programme again unde

  • Passing const vecter in a class function

    I am trying to initialize a const vecter in a class but I cannot finger out what is wrong. I have not program for a few years I finally got back into it. class bag { Public:     bag();     bag(const vector<char> &v); Private: const vector<char>v; bag