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

Similar Messages

  • 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

  • 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

  • Sum in where clause

    can i use sum in where clause
    eg
    select from table_name id_klient,name,lastname,sum(number_of_products)
    from Klients k,Sales s
    where k.id_klient=s.id_klient
    and sum(number_of_products)>100

    or
    select a.id_klient,
           a.name,
           a.lastname,
           a.tot_prod
      from (select id_klient,
                   name,
                   lastname,
                   sum(number_of_products) tot_prod
              from Klients k,
                   Sales   s
             where k.id_klient = s.id_klient
             group by id_klient, name, last_name) a
    where a.tot_prod > 100note: untested

  • 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;

  • ORA-10914: invalid TABLESPACE GROUP clause

    hai im trying to create a database in oracle 10g
    tablespace sysaux datafile 'E:\oracle\product\10.1.0\oradata\multi\ts_sysaux01.d
    bf' size 10m autoextend on extent management local
    ERROR at line 9:
    ORA-10914: invalid TABLESPACE GROUP clause
    can any one explain me ,
    regards,
    ashik

    first i thank u mr.venkat and user526020 for replied for ,
    here i enclosed my database creation for ur ref,
    create database multi logfile
    group 1 'E:\oracle\product\10.1.0\oradata\multi\redo01.log' size 10m,
    group 2 'E:\oracle\product\10.1.0\oradata\multi\redo02.log' size 10m,
    group 3 'E:\oracle\product\10.1.0\oradata\multi\redo03.log' size 10m
    datafile 'E:\oracle\product\10.1.0\oradata\multi\system01.dbf' size 10m autoextend on
    default tablespace users datafile 'E:\oracle\product\10.1.0\oradata\multi\ts_users01' size 10m autoextend on extent management local
    default undo tablespace undotbs datafile 'E:\oracle\product\10.1.0\oradata\multi\ts_undotbs01.dbf' size 10m autoextend on
    default temporary tablespace temptbs tempfile 'E:\oracle\product\10.1.0\oradata\multi\ts_temptbs01.tmp' size 10m autoextend on
    tablespace sysaux datafile 'E:\oracle\product\10.1.0\oradata\multi\ts_sysaux01.dbf' size 10m autoextend on extent management local
    character set al32utf8
    SYS at multi>/
    tablespace sysaux datafile 'E:\oracle\product\10.1.0\oradata\multi\ts_sysaux01.d
    bf' size 10m autoextend on extent management local
    ERROR at line 9:
    ORA-10914: invalid TABLESPACE GROUP clause
    here im getting error only on sysaux tablespace size then i tried to increase the size even it shows the same,
    so can any one give solution.
    regards,
    ashik

  • MERGE statement without INSERT clause....is possible...?

    Hi everybody...
    MERGE statement without UPDATE or INSERT clause is possible or not
    I want to select from one table and update in another table. So i dont want insert statement and i want to do it in single query....possible solutions are requested.
    Thanks in advance
    pal

    Hi..
    Thanks for ur reply. For MERGE statement, we have to give UPDATE and INSERT clause. this MERGE statement works without INSERT or UPDATE clause.
    Why i am asking is, I want to select how many rows (count(*)) from table1 and based on this count, i have to update in table2
    Both tables r different and for select and for update where clauses are different. Both tables r totally different.
    I want to do it in single query, so i asked this is possible with MERGE statement without INSERT clause.
    Thanks for ur reply

  • 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

  • Can we write query for fomatted search without from clause

    can we write query for fomatted search without from clause as below.
    SELECT (($(u_amt)*14)/100)
    here U_amt is a UDF .I want to assign this to another field .
    Rgds,
    Rajeev

    Hi Rajeev,
    You can write query for FMS without from.  That is because you can omit it when you get value from active form by default.  The grammar of it is:
    Select $[$38.u_amt.0\] * 14/100 in your case if you have item type marketing document @line level.
    From View-System Information, you can get the info you need for your FMS query at the left bottom of your screen.
    Thanks,
    Gordon

  • What happens u0093Updateu0094 command is used without where clause ?

    Hi
    What happens “Update” command is used without where clause ? 
    thank you

    Hi subash,
    chk this help
    UPDATE  dbtab      SET f1 ... fn. or
    UPDATE (dbtabname) SET f1 ... fn.
    Extras:
    1. ... WHERE condition
    2. ... CLIENT SPECIFIED
    3. ... CONNECTION con
    Effect
    Updates values in a database table. <b>If there is no WHERE clause, all lines (in the current client) are updated.</b> If a WHERE condition is specified, only thoserecords which satisfy the WHERE condition are updated.

  • 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

  • Group by with and without where clause

    Do I need to use these two inner views to show results by group by as one line? Can I achieve the same result without typing the same select statement two times since these two SELECT statements differ only in where clause. This query is a simulation. My actual query is longer. My expectation is to make this query shorter (without inner views).
    with tmp as (
    select 'COMPLETE' status, 'GERMANY' country, 0 substatus FROM dual UNION ALL
    select 'COMPLETE' status, 'GERMANY' country, 1 substatus FROM dual UNION ALL
    select 'COMPLETE' status, 'GERMANY' country, 0 substatus FROM dual)
    select v1.status, v1.country, v1.cnt01, v2.cntIncluding0 from
    (select status, country, count(*) cnt01 from tmp tmp1 group by status, country) v1
    JOIN
    (select status, country, count(*) cntIncluding0 from tmp tmp2 where substatus=0 group by status, country) v2
    on v1.status=v2.status and v1.country=v2.country;

    totalnewby wrote:
    Do I need to use these two inner views to show results by group by as one line? Can I achieve the same result without typing the same select statement two times since these two SELECT statements differ only in where clause. This query is a simulation. My actual query is longer. My expectation is to make this query shorter (without inner views).
    with tmp as (
    select 'COMPLETE' status, 'GERMANY' country, 0 substatus FROM dual UNION ALL
    select 'COMPLETE' status, 'GERMANY' country, 1 substatus FROM dual UNION ALL
    select 'COMPLETE' status, 'GERMANY' country, 0 substatus FROM dual)
    select v1.status, v1.country, v1.cnt01, v2.cntIncluding0 from
    (select status, country, count(*) cnt01 from tmp tmp1 group by status, country) v1
    JOIN
    (select status, country, count(*) cntIncluding0 from tmp tmp2 where substatus=0 group by status, country) v2
    on v1.status=v2.status and v1.country=v2.country;
    SQL> with tmp as
      2  (
      3  select 'COMPLETE' status, 'GERMANY' country, 0 substatus FROM dual UNION ALL
      4  select 'COMPLETE' status, 'GERMANY' country, 1 substatus FROM dual UNION ALL
      5  select 'COMPLETE' status, 'GERMANY' country, 0 substatus FROM dual
      6  )
      7  select status,
      8         country,
      9         count(substatus) cnt01,
    10         sum(decode(substatus, 0, 1, 0)) cntincluding0
    11    from tmp
    12   group by status, country
    13  ;
    STATUS   COUNTRY      CNT01 CNTINCLUDING0
    COMPLETE GERMANY          3             2

Maybe you are looking for

  • HP LaserJet CP1525nw Printing Problems.

    Before I begin I should tell you that we have 2 ipad 2's in the house.  My Wifes iPad 2 and my iPad 2.  My iPad 2 works just fine and as intended.  For my wife iPad 2 she can not print from it.  It will show the printer as a wireless printer on her i

  • How do I save an image when there is a link attached?

    At times I run across an image that I want to "save" but it has a link attached to it, usually a link to the site's home page. When the link is there I am not given an option to save the image, just options relating to the link. How can I save such a

  • AS3.0 Save pdf option

    Hi surfers, Flash Actionscript 3.0. How to save Movieclip to pdf Format with high resolution. Help for me Thanks in Advance.

  • Why am I receiving "iMessage Activation: could not sign in . Please check your network connection and try agin."

    Why am I receiving iMessage activation "could not sign in. Please check your network connections and try again? I am connected to the network.

  • UIScrollBar not showing arrows

    I'm working on an FLA from templatemonster, you know, the ones with a lot of nested MCs and default named layers. What I'm Trying To Do Add the UIScrollBar component to a dynamic text box. Symptoms of the Problem Just displays a white rectangular box