Group by clause based on condition

tblScore contains score for each problem
id     problemID      score
1          1             10
2          2             30
tblSubmission contains problem submissions for each user
id     user         problemID      accepted
1     UserA             1                 0
2     UserA             1                 0
3     UserA             1                 1
4     UserA             2                 1
5     UserB             1                 0
6     UserB             1                 1
7     UserB             2                 1
Explanation  :
For UserA :
 -  For problemID 1
      ->  submitted three times
      ->  rejected for first two submission and accepted on third submission.
 - For problemID 2
      -> submitted one time
      -> accepted on first submission
For UserB :
 -  For problemID 1
      ->  submitted two times
      ->  rejected for first submission and accepted on second submission.
 - For problemID 2
      -> submitted one time
      -> accepted on first submission
Now I would like to process the table and want to get the following result :
user              Score
UserA             36 (6 + 30)
UserB             38 (8 + 30)
Explanation :
- For each rejected submission, a -2 point penalty.
- UserA have submitted probelmID 1
  - > score of problemID 1 is 10.
  - > first two times rejectd
  - > third time accepted.
  -> score = 10 - 4 = 6
- UserA have submitted problemID 2
  - > score of problemID 2 is 30
  - > first time accepted. No penalty will be counted
  - > score = 30
so final score for UserA = 30 + 6 = 36
Similar for UserB.
I know all I am doing is explanations. I have tried a lot with gorup by and other stuffs. May be my lack of knowledge on SQL is the problem.
I would really appreciate if someone help me on this.
Thank You

Please post DDL,so that people do not have to guess what the keys,constraints,Declarative Referential Integrity,data types,etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. You have no idea,and
you even tibbled and used singular table names! Temporal data should use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
This is minimal polite behavior on SQL forums. 
You have a magical,generic “id”,which does not exist in RDBMS. We would use a “<something>_id” instead. We need a key to make this a table. 
CREATE TABLE Scores
(problem_nbr INTEGER NOT NULL PRIMARY KEY,
 problem_score INTEGER NOT NULL
   CHECK (problem_score > 0));
INSERT INTO Scores
VALUES (1,10), (2,30);
Your next table is wrong, too. SQL is a declarative language and we do not use assembly language flags. 
CREATE TABLE Submissions 
(user_name CHAR(5) NOT NULL,
 problem_nbr INTEGER NOT NULL,
 submission_nbr INTEGER NOT NULL,
 PRIMARY KEY (user_name, problem_nbr, submission_seq),
 score INTEGER DEFAULT -2 NOT NULL);
INSERT INTO Submissions
VALUES
('UserA', 1, 1, -2), 
('UserA', 1, 2, -2), 
('UserA', 1, 3, 10), 
('UserA', 2, 1, 30), 
('UserB', 1, 1, -2), 
('UserB', 1, 2, 10), 
('UserB', 2, 1, 30);
You need a procedure to insert test result into the table. But do you stop when you get a passing grade? 
CREATE PROCEDURE Post_Test_Results
(@in_user_name CHAR(5),
 @in_problem_nbr INTEGER,
 @in_pass_fail CHAR(4))
AS
INSERT INTO Submissions
SELECT @in_user_name, @in_problem_nbr, 
       CASE WHEN @in_pass_fail = 'pass'
            THEN S.problem_score
            ELSE -2 END;
  FROM Scores AS S
 WHERE S.problem_nbr = @in_problem_nbr;
Put the answer in a VIEW, so itis always right and current:
CREATE VIEW Final_Scores
AS
SELECT user_name, problem_nbr, SUM(score) AS final_score 
  FROM Submissions
 GROUP BY user_name, problem_nbr;
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • Newbie Dynamic Group by clause

    Example
    create table test( awhite numeric(6,0)
    , DMonth numeric(2,0)
    , Goalnumber numeric(2,0)
    , Objnumber numeric(2,0));
    insert into test(awhite,DMonth,Goalnumber,Objnumber)
    values(5,6,1,1);
    insert into test(awhite,DMonth,Goalnumber,Objnumber)
    values(8,6,1,2);
    insert into test(awhite,DMonth,Goalnumber,Objnumber)
    values(12,6,2,1);
    insert into test(awhite,DMonth,Goalnumber,Objnumber)
    values(16,10,2,1);
    insert into test(awhite,DMonth,Goalnumber,Objnumber)
    values(4,10,2,1);
    ===========================
    I need this to be ONE query with a parameter
    Select SUM(Awhite) SWhite
    ,DMonth
    ,CASE WHEN &groupbyobj<2 THEN
    to_number('99')
    ELSE
    Goalnumber
    END Goalnumber
    ,CASE WHEN &groupbyobj<3 THEN
    to_number('99')
    ELSE
    Objnumber
    END Objnumber
    FROM Test
    GROUP BY Goalnumber,Objnumber,DMonth
    ============================
    So when the groupbyobj=3, I want the output to look like
    SWHITE DMONTH GOALNUMBER OBJNUMBER
    5 6 1 1
    8 6 1 2
    12 6 2 1
    20 10 2 1
    ==============================
    So when the groupbyobj=2, I want it grouped by GOALNUMBER
    SWHITE DMONTH GOALNUMBER OBJNUMBER
    13 6 1 99
    12 6 2 99
    20 10 2 99
    So when the groupbyobj=1, I want it grouped by DMonth
    SWHITE DMONTH GOALNUMBER OBJNUMBER
    25 6 99 99
    20 10 99 99
    I ADDED the above "99" to the output above. I could not get my query to output that.
    QUESTION- How can I create A DYNAMIC Group by clause based on the parameter
    (Groupbyobj) Selected?
    TIA
    Steve42

    I noticed I got the numbers 1 until 3 just the other way round, so here is a new version.
    SQL> var P_GROUPING_SET number
    SQL> exec :P_GROUPING_SET := 1
    PL/SQL-procedure is geslaagd.
    SQL> select sum(awhite) swhite
      2       , dmonth
      3       , nvl(goalnumber,99) goalnumber
      4       , nvl(objnumber,99) objnumber
      5    from test
      6   group by dmonth
      7       , rollup(goalnumber,objnumber)
      8  having case grouping_id(goalnumber,objnumber)
      9           when 0 then 3
    10           when 1 then 2
    11           when 3 then 1
    12         end = :P_GROUPING_SET
    13  /
        SWHITE     DMONTH GOALNUMBER  OBJNUMBER
            25          6         99         99
            20         10         99         99
    2 rijen zijn geselecteerd.
    SQL> exec :P_GROUPING_SET := 2
    PL/SQL-procedure is geslaagd.
    SQL> select sum(awhite) swhite
      2       , dmonth
      3       , nvl(goalnumber,99) goalnumber
      4       , nvl(objnumber,99) objnumber
      5    from test
      6   group by dmonth
      7       , rollup(goalnumber,objnumber)
      8  having case grouping_id(goalnumber,objnumber)
      9           when 0 then 3
    10           when 1 then 2
    11           when 3 then 1
    12         end = :P_GROUPING_SET
    13  /
        SWHITE     DMONTH GOALNUMBER  OBJNUMBER
            13          6          1         99
            12          6          2         99
            20         10          2         99
    3 rijen zijn geselecteerd.
    SQL> exec :P_GROUPING_SET := 3
    PL/SQL-procedure is geslaagd.
    SQL> select sum(awhite) swhite
      2       , dmonth
      3       , nvl(goalnumber,99) goalnumber
      4       , nvl(objnumber,99) objnumber
      5    from test
      6   group by dmonth
      7       , rollup(goalnumber,objnumber)
      8  having case grouping_id(goalnumber,objnumber)
      9           when 0 then 3
    10           when 1 then 2
    11           when 3 then 1
    12         end = :P_GROUPING_SET
    13  /
        SWHITE     DMONTH GOALNUMBER  OBJNUMBER
             5          6          1          1
             8          6          1          2
            12          6          2          1
            20         10          2          1
    4 rijen zijn geselecteerd.

  • Conditional GROUP BY clause

    Hi,
    I have four columns in group by clause. I want to add conditional group by clause.
    Case 1 : If one of the  column's value is null, I don't want to include it in group by clause. Means, Now GROUP BY clause will have only 3 columns.
    Case 2 : If not null, then GROUP BY clause with all four columns.
    Please help me out on this.
    Thanks in advance.  

    Hi
    I think it won't matter, all group functions by default ignore NULLs so your result won't differ.
    select  dept, loc, sum(sal)
    from (
    select 'A' emp , 1 dept , 'P' loc , 100 sal from dual union all
    select'B',1,'P',200 from dual union all
    select'C',2,'P',300 from dual union all
    select'D',2,'P',400 from dual union all
    select'E',3, 'P',500 from dual union all
    select'F',3, 'P',600 from dual union all
    select'G',4, 'Q',700 from dual union all
    select'H', null,'Q' , 1000 from dual union all
    select'I',null ,'Q', 2000 from dual union all
    select 'J' ,null, 'Q',300 from dual)
    group by dept,loc;
    Output
    DEPT      LOC      SUM(SAL)
    1                P      300
    2                P      700
    3                P      1100
                    Q      3300
    4                Q      700
    Now by doing grouping only for NOT NULL values,
    select dept,loc, sum(sal)
    from (
    select 'A' emp , 1 dept , 'P' loc , 100 sal from dual union all
    select'B',1,'P',200 from dual union all
    select'C',2,'P',300 from dual union all
    select'D',2,'P',400 from dual union all
    select'E',3, 'P',500 from dual union all
    select'F',3, 'P',600 from dual union all
    select'G',4, 'Q',700 from dual union all
    select'H', null,'Q' , 1000 from dual union all
    select'I',null ,'Q', 2000 from dual union all
    select 'J' ,null, 'Q',300 from dual)
    where dept is not null          --------------NOT NULL Condition
    group by dept, loc;
    Output
    DEPT     LOC      SUM(SAL)
    1           P           300
    2           P           700
    3           P           1100
    4           Q           700
    Now by doing grouping only for NULL values,
    select dept,loc, sum(sal)
    from (
    select 'A' emp , 1 dept , 'P' loc , 100 sal from dual union all
    select'B',1,'P',200 from dual union all
    select'C',2,'P',300 from dual union all
    select'D',2,'P',400 from dual union all
    select'E',3, 'P',500 from dual union all
    select'F',3, 'P',600 from dual union all
    select'G',4, 'Q',700 from dual union all
    select'H', null,'Q' , 1000 from dual union all
    select'I',null ,'Q', 2000 from dual union all
    select 'J' ,null, 'Q',300 from dual)
    where dept is null               --------------NULL Condition
    group by dept, loc;
    Output
    DEPT      LOC         SUM(SAL)
                    Q           3300
    The output is same for both the conditions.

  • Oracle 10g group by clause

    I have one SQL query using a GROUP BY clause and no ORDER BY clause is used. When executed in Oracle 8i, the query results are returned ordered by first column mentioned in the GROUP BY clause. When the same query is executed in Oracle 10g, the query results are returned withour ordering the data by the first column in the GROUP BY clause. It works only when I explicitly mention the ORDER BY clause. Can you please explain this? In Orcale 8i, is it that, by default, the data is ordered by the first column mentioned in the GROUP BY clause when ORDER BY clause is not mentioned?
    In which order does oracle 10g sorts when I use group by clause in oracle 10g

    [email protected] wrote:
    the use of group by is to group based on some column value, in this case why does the the output differs in rows. why does the output, when you use group by is not the following formatSorry, but this is a totally fruitless topic. Why are you bothering with something that is totally internal to the DBMS? If you want the data ordered, use ORDER BY, it's that simple.
    Check out this link, if you want some discussion on it:
    [http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:74320098178823]

  • Alternate to group by clause

    Hi
    I am using Oracle 8i and one of my queries is getting the data from multiple sources through a dblink from other databases (customer need cannot avoid dblinks).
    The query is using the group by clause to get the count based on specific columns and when i am not using the group by the query is pretty fast.
    select count(id), col1,col2,col3
    from source1@dblink1,
    source2@dblink1,
    source3@dblink1,
    source4@dblink1,
    source5@dblink1
    where
    group by col1,col2,col3
    Please suggest the use of other Oracle features that we can use (pl/sql table or looping in pl/sql instead of using group by ) as the amount of data is large and it has to go through several iterations and accordingly update my local db with the counts returned.
    An example will be quite helpful.
    Thanks in Advance.

    Hi,
    i have a procedure that has a cursor thats using db links as above, in the code if i open the cursor and say NULL even then it is taking about 8 mins while the cursor query is taking about 2 mins only when run separately.
    i open the cursor
    for c1 in cursor loop
    NULL;
    end loop;
    it hangs on for about 8 mins , while if i run the query of the cursor with the same parameters that i pass in the cursor at run time it takes about 2 mins.
    Dont understand where the 6 mins are going.
    If the cursor is not opened at all in the proc it gets executed in less than a second so there is no other code thats consuming time.
    Please suggest.

  • Group by clause will try to group the primay key's

    hi all,
    For my requiremments and to avoid the the subquery i am using join and group by clause in my sql query in oracle 10g r2 database.my question is if i put a primary column the group clause then oracle try to group the records?.
    i know if we use a primary key column in group by clause there is no grouping will occur.
    but i have doubt oracle will try to group ? because it will take some amount of time to achive?
    else due presense of primay key column in group by clause oracle won't try?
    Please advice ??

    My query return the records less then the min v_date(date datatype) column.
    i check this condition in having clause
    my old query is
    select emp_id,emp_name,voldate,volume,productivity
    from volume v1
    where v1.voldate<=(select min(v2.voldate) form volume v2 where v2.emp_id=1)
    and v1.emp_id=1
    i change it as
    select emp_id,emp_name,voldate,volume,productivity
    from volume v1,volume v2
    where v1.emp_id=v2.emp_id
    having v1.voldate<=min(v2. voldate)
    group by emp_id,emp_name,voldate,volume,productivity
    above the query's emp_id is primay key for volume table
    comparing both query's which one is the best while looking th response time.
    else any other alternative for both the queries.??

  • Reg - Search Form for a VO with group by clause

    Hi,
    I have a Bar graph that displays data based on the Query below.
    SELECT STATUS.STATUS_ID AS STATUSID,STATUS.STATUS,COUNT(SR.SERVICEREQUEST_ID) AS SRCOUNT
    FROM SERVICE_REQUEST SR ,SERVICEREQUESTSTATUS STATUS
    WHERE SR.STATUS_ID = STATUS.STATUS_ID
    GROUP BY STATUS.STATUS_ID,STATUS.STATUS,SR.STATUS_ID
    It displays the count of SRs against a particular status.
    Now I need to add a search form to this graph with customer and date range.
    So we need to add the line below to the where clause.
    "SR.CUSTOMER_ID = :customerId AND SR.REQUESTED_ON BETWEEN :fromDate and :toDate"
    But the columns SR.CUSTOMER_ID, SR.REQUESTED_ON also need to be added to the select clause to create the View criteria for search panel.
    The two columns should also need to be added to the group by clause if we are to add them in the select clause.
    This would not produce the expected results.
    How do I create a search form with the criterias applied only at the where clause.Please help.
    With Regards,
    Guna

    The [url http://docs.oracle.com/cd/E16162_01/apirefs.1112/e17483/oracle/jbo/server/ViewObjectImpl.html]ViewObjectImpl has methods for doing this programmatically (setQuery, defineNamedWhereClauseParam, setNamedWhereClauseParam) that you can use to manipulate the query, the bind variables expected, and the values for the binds.
    John

  • Problem trying to use a group by clause

    hey good day,
    i'm trying to use a group by clause in my application, but I'm getting the following error.
    Error:-  Query cannot be parsed, please check the syntax of your query. (ORA-00979: not a GROUP BY expression)
    select      "INSTRUCTOR"."EMPNUM",
          "INSTRUCTOR"."FIRSTNAME",
          "INSTRUCTOR"."LASTNAME",
          "QUALN"."SPECIALIZE_FIELD" as "SPECIALIZE_FIELD",
             "INSTRUCTOR"."USERNAME"
    from      "QUALN" "QUALN",
          "INSTRUCTOR" "INSTRUCTOR"
    where   "INSTRUCTOR"."EMPNUM"="QUALN"."EMPNUM"
    group by "INSTRUCTOR"."EMPNUM", "INSTRUCTOR"."FIRSTNAME", "INSTRUCTOR"."LASTNAME"Thanks in advance,
    Richie

    Richie wrote:
    hey thanks for your reply,
    i have tried what you have suggested, but now i got another error
    Error :- The report query needs a unique key to identify each row. The supplied key cannot be used for this query. Please edit the report attributes to define a unique key column. ORA-01446: cannot select ROWID from, or sample, a ...
    This error message is not from oracle, btu from your reporting tool. it might be MS Access or whatever other tool that you use. Some of these tools want a unique value to identify the current row. The logic applied depends on the relationship of your tables. however in your case you could do it without the group by condition. THen the rowid can still be applied to your query.
    Example
    note the usage of alias names to simplified the select
    select      i.EMPNUM ,
          i.FIRSTNAME ,
          i.LASTNAME ,
             i.USERNAME
    from      INSTRUCTOR i
    where   i.EMPNUM in (select q.EMPNUM from QUALN q);

  • Extracting from table based on conditions from two internal tables

    Hi,
         i to have select few records from  a table based on conditions from two different internal tables. How can I achieve this.?
    ex:
          select objid from HRVPAD25 into table t_pad25
                                                    where PLVAR = 01
                                                                OTYPE = E
                                                                OBJID = itab1-sobid
                                                                sobid = itab2-pernr.
    How can this be written? can i use "for all entries..." addition with 2 tables?

    Hi Maansi_SAP,
    you can use exactly one internal table in the FOR ALL ENTRIES clause. Consider this alternative:
    data:
      itab_sobid_hash like itab1 with unique key sobid,
      ls_pad25  like line of  t_pad25.
    sort itab1.
    delete adjacend duplicates from itab1 comparing sobid.
    itab_sobid_hash = itab1.
    select objid
      into ls_pad25
      from HRVPAD25
      for all entries in itab2
      where PLVAR = '01'
        and OTYPE = E
        and sobid = itab2-pernr..
    read table itab_sobid_hash with table key sobid = ls_pad25-objid.
    check sy-subrc = 0.
    append ls_pad25 to t_pad25.
    endselect.
    You may decide if itab1 or itab2 is better used as hashed table. Make a performance test.
    The critics will tell you that SELECT ... ENDSELECT is not performant. That was very true, back in last milleniums's 90ies
    Regards,
    Clemens

  • Adding subquery to query w/ Group By clause crashes

    Hello all! I am trying to add in the subquery to the statement below. The query works fine before I add in the subquery, but after adding the subquery it will time out. If I comment out the MIN(table1.EOD_DATE) and the Group By clause, the query works fine.
    I do not want to do this I need those two items. What am I missing here? Any ideas are appreciated, thanks!
    SELECT table1.FUND,
    table1.DEPT,
    table1.ORG,
    table1.ACCT,
    LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||SUBSTR(table1.ACCT,1,2) acct_no,
    LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||table1.ACCT acct_no1,
    table2.FUND,
    table2.DEPT,
    table2.ORG,
    table2.ACCT
    MIN(table1.EOD_DATE)
    FROM table1,
    table2
    WHERE table1.fund BETWEEN substr(:P_ACCT_FROM,0,3) AND substr(:P_ACCT_TO,0,3)
    ANDtable1.dept BETWEEN substr(:P_ACCT_FROM,4,2) AND substr(:P_ACCT_TO,4,2)
    ANDtable1.org BETWEEN substr(:P_ACCT_FROM,6,4) AND substr(:P_ACCT_TO,6,4)
    ANDtable1.acct BETWEEN substr(:P_ACCT_FROM,10,5) AND substr(:P_ACCT_TO,10,5)
    AND floor(table1.acct/10000) in (6,8)
    AND SUBSTR(table1.acct,3) != '000'
    ANDtable1.eod_date BETWEEN :p_from_date AND :p_to_date
    AND table2.fund (+)=table1.fund
    AND table2.dept (+)=table1.dept
    AND table2.org (+)=table1.org
    AND table2.acct (+)=table1.acct
    AND table2.type IN( 'PI','JE','PR','VD','VU','AC','AD')
    AND table2.po_no IN
    SELECT trans.po_no
    FROM table2 trans LEFT OUTER JOIN req ON trans.po_no = req.po_no
    WHERE (trans.po_no IS NULL OR (TO_CHAR(req.open_date,'YYYY')) = (TO_CHAR(:p_year,'FM9999')))
    GROUP BY table1.fund,
    table1.dept,
    table1.org,
    table1.acct,
    table2.fund,
    table2.dept,
    table2.org,
    table2.acct
    ORDER BY LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||SUBSTR(table1.ACCT,1,2),
    LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||table1.ACCT

    Some untested comments;
    AND floor(table1.acct/10000) in (6,8)
    AND SUBSTR(table1.acct,3) != '000'Can these two conditions be combined, ie is this the same as;
    AND (table1.acct LIKE '0006%' OR table1.acct LIKE '0008%')Ignoring the hard coded dates (assumed they where used for testing) you should avoid using implicit conversions and two digit years;
    AND trans.activity_date BETWEEN TO_CHAR('01-jan-2007', 'dd-mon-yyyy') AND TO_CHAR('01-feb-2007', 'dd-mon-yyyy')You can convert your parameters once rather than converting every row by making hte parameter match the column data type;
    AND (   trans.po_no IS NULL
         OR req.open_date BETWEEN TO_DATE('01-JAN-' || TO_CHAR(:p_year,'9999') || ' 00:00:00' ,'DD-MON-YYYY HH24:MI:SS')
                              AND TO_DATE('31-DEC-' || TO_CHAR(:p_year,'9999') || ' 23:59:59' ,'DD-MON-YYYY HH24:MI:SS')
        )

  • Using indexes when using group by clause

    How can I make use of indexes when there is a group by clause in the sql/ pl/sql. Heard that when ever there is a group by clause , sql bypasses use of indexes. Is it true?
    Thanks in advance

    Hi,
    Depending on the query containing the group by, indexes will still be used.
    For example, create a big table based on the all_objects table. Then create an index on the object_type column. Then run this query:
    select count(*), object_type from big_table where object_type != 'PACKAGE' group by object_type
    The execution plan for this query will show the index to be used, the group by does not prevent the optimizer from using an index. Then run this query:
    select count(*), object_type from big_table group by object_type
    The execution plan for this query will show the index not to be used because the whole table - no restrictions - needs to be read to get the result.
    Hope this helps!
    Regards,
    Marco Stuijvenberg
    =
    www.marcostuijvenberg.nl

  • Group by clause and having clause in select

    hi frnds
    plz give me some information of group by and having clause used in select statement with example
    thanks

    The Open SQL statement for reading data from database tables is:
    SELECT      <result>
      INTO      <target>
      FROM      <source>
      [WHERE    <condition>]
      [GROUP BY <fields>]
      [HAVING   <cond>]
      [ORDER BY <fields>].
    The SELECT statement is divided into a series of simple clauses, each of which has a different part to play in selecting, placing, and arranging the data from the database.
    You can only use the HAVING clause in conjunction with the GROUP BY clause.
    To select line groups, use:
    SELECT <lines> <s1> [AS <a1>] <s2> [AS <a2>] ...
                   <agg> <sm> [AS <am>] <agg> <sn> [AS <an>] ...
           GROUP BY <s1> <s2> ....
           HAVING <cond>.
    The conditions <cond> that you can use in the HAVING clause are the same as those in the SELECT clause, with the restrictions that you can only use columns from the SELECT clause, and not all of the columns from the database tables in the FROM clause. If you use an invalid column, a runtime error results.
    On the other hand, you can enter aggregate expressions for all columns read from the database table that do not appear in the GROUP BY clause. This means that you can use aggregate expressions, even if they do not appear in the SELECT clause. You cannot use aggregate expressions in the conditions in the WHERE clause.
    As in the WHERE clause, you can specify the conditions in the HAVING clause as the contents of an internal table with line type C and length 72.
    Example
    DATA WA TYPE SFLIGHT.
    SELECT   CONNID
    INTO     WA-CONNID
    FROM     SFLIGHT
    WHERE    CARRID = 'LH'
    GROUP BY CONNID
    HAVING   SUM( SEATSOCC ) > 300.
      WRITE: / WA-CARRID, WA-CONNID.
    ENDSELECT.
    This example selects groups of lines from database table SFLIGHT with the value ‘LH’ for CARRID and identical values of CONNID. The groups are then restricted further by the condition that the sum of the contents of the column SEATSOCC for a group must be greater than 300.
    The <b>GROUP BY</b> clause summarizes several lines from the database table into a single line of the selection.
    The GROUP BY clause allows you to summarize lines that have the same content in particular columns. Aggregate functions are applied to the other columns. You can specify the columns in the GROUP BY clause either statically or dynamically.
    Specifying Columns Statically
    To specify the columns in the GROUP BY clause statically, use:
    SELECT <lines> <s1> [AS <a 1>] <s 2> [AS <a 2>] ...
                   <agg> <sm> [AS <a m>] <agg> <s n> [AS <a n>] ...
           GROUP BY <s1> <s 2> ....
    To use the GROUP BY clause, you must specify all of the relevant columns in the SELECT clause. In the GROUP BY clause, you list the field names of the columns whose contents must be the same. You can only use the field names as they appear in the database table. Alias names from the SELECT clause are not allowed.
    All columns of the SELECT clause that are not listed in the GROUP BY clause must be included in aggregate functions. This defines how the contents of these columns is calculated when the lines are summarized.
    Specifying Columns Dynamically
    To specify the columns in the GROUP BY clause dynamically, use:
    ... GROUP BY (<itab>) ...
    where <itab> is an internal table with line type C and maximum length 72 characters containing the column names <s 1 > <s 2 > .....
    Example
    DATA: CARRID TYPE SFLIGHT-CARRID,
          MINIMUM TYPE P DECIMALS 2,
          MAXIMUM TYPE P DECIMALS 2.
    SELECT   CARRID MIN( PRICE ) MAX( PRICE )
    INTO     (CARRID, MINIMUM, MAXIMUM)
    FROM     SFLIGHT
    GROUP BY CARRID.
      WRITE: / CARRID, MINIMUM, MAXIMUM.
    ENDSELECT.
    regards
    vinod

  • Replication based on condition for whole Schema

    Hi There
    Oracle 11.1.0.7
    We are using oracle spatial and we have got huge tables of size more than 50 GB . I just started configuring GG on test and i would like to know if it suits our requirement.
    In this regards i have certain queries :
    1) Can i configure GG for whole schema based on conditions , for example in the schema there are 300 tables , out of those i want all 250 to replicate at the target as is and the rest 50 should replicate on where approved = 'YES' . Is this possible ?
    2) If its possible to filter data during replication , i would like to know if we can filter using a query which has a 'JOIN'
    3) Should the target database (Oracle 11.1.0.7) have the tables with the data as on before starting GG so that when we start replicating both source and target should be exactly the same.
    I appreciate if some one can post a response.
    Thanks

    You can filter data using a WHERE clause, or even using SQLEXEC, mapping OUT values to target columns. A join could be handled in the output from a stored procedure.
    You can do all tables or a portion thereof. If names are similar, they can be wildcarded. Otherwise, list them.
    Not sure what you mean by APPROVED.
    For initial load, the stock answer is this:
    GoldgenGate recommends using native RDBMS tools for the initial load. Restore a backup, that kind of drill. You can use one of the four GG initial load options, but given the size you mentioned, it would probably be much faster to create the target via Oracle Data Pump or RMAN.

  • Why is the GROUP BY clause not working in my Query?

    Dear All,
    Below is the Query for a Summary Debtors Aged Analysis.
    The GROUP BY clause does not seem to be working.
    The Query returns all the unpaid invoices, instead of a single total row for each Customer.
    If a Customer X has 10 unpaid invoices, 10 rows are displayed - one for each invoice.
    I was expecting only 1 row for Customer X, 1 for Customer Y, etc.
    This is what GROUP BY is supposed to do, but it is not doing its work.
    What has gone wrong?
    Thanks
    Leon Lai
    Here's my Query:
    declare @taxdt datetime
    set @taxdt
    /*select 1 from jdt1 t0 where t0.TaxDate*/ = [%1]
    SELECT
    CASE
                 WHEN T0.Account = 1220101 THEN 'Prim Cust'
                 WHEN T0.Account = 1220102 THEN 'Fgn Cust'
                 WHEN T0.Account = 1220103 THEN 'Local Cust'
                 WHEN T0.Account = 1220104 THEN 'Staff Loan' 
                 WHEN T0.Account = 1220105 THEN 'Dep with TP'
                 WHEN T0.Account = 1220106 THEN 'Adv to Cust'
                 WHEN T0.Account = 1220108 THEN 'Sund Drs'
                 ELSE 'Error ! ! !'
    END AS 'Control A/c',
    T1.CardCode AS 'BP Code',
    T2.Notes2 AS 'BP Name',
    SUM ((T0.Debit - T0.Credit)) AS 'Orig. Rs',       
    SUM ((T0.BalDueDeb - T0.BalDueCred)) AS 'Bal. Rs',     
    ((SELECT SUM(T0.BalDueDeb) - Sum(T0.BalDueCred)
        WHERE DateDiff(mm, T0.TaxDate, @taxdt) = 1))    
        AS '1 Mth Ago' 
    /* Similarly for other age brackets*/
    FROM JDT1 T0
    INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    LEFT OUTER JOIN OCPR T2 ON T1.CardCode = T2.Cardcode
    LEFT OUTER JOIN OJDT T3 ON T0.TransID = T3.TransID
    LEFT OUTER JOIN OINV  T4 ON T3.TransID = T4.TransID
    LEFT OUTER JOIN ORIN  T5 ON T3.TransID = T5.TransID
    WHERE
    T1.CardType = 'C'
    and (Balance) != 0
    and (T0.BalDueDeb - T0.BalDueCred) != 0
    GROUP BY T0.Account, T1.CardCode, T2.Notes2, T0.TaxDate

    Dear Neetu,
    Thanks for your reply.
    This Query is a modification of the Query you posted in SAP B1 SQL TIPS & TRICKS
    http://wiki.sdn.sap.com/wiki/display/B1/SAPB1SQLB-FNDebtorsAgingReportbydate
    So, maybe instead of referring to my Query, let's refer to yours. It may be easier for you to understand me.
    Once I understand the problem, I can adapt your query to suit my requirements
    So, let's start with a clean slate:
    The Query you have posted is for a DETAILED Debtors Aging Report.
    This lists all outstanding invoices, and ages them in the Age Brackets.
    What I want is a SUMMARY Debtors Aging Report.
    This will give the total amount owed by each Customer, and this amount is broken down in the Age Bracket Columns
    There will be a single row listed for each customer, something like this:
    Customer     Total Due     Current      1 Mth          2 Mth         3 Mth  etc
    Alfred       500,000       300,000       200,000
    Charles      800,000                     100,000       300,000       400,000
    How can you modify your query to make it become a Summary Report (1 line for each customer even if he has many invoices)?
    Thanks
    Leon Lai
    Here's your code
    SELECT T1.CardCode, T1.CardName, T1.CreditLine, T0.RefDate, T0.Ref1 'Document Number',
         CASE  WHEN T0.TransType=13 THEN 'Invoice'
              WHEN T0.TransType=14 THEN 'Credit Note'
              WHEN T0.TransType=30 THEN 'Journal'
              WHEN T0.TransType=24 THEN 'Receipt'
              END AS 'Document Type',
         T0.DueDate, (T0.Debit- T0.Credit) 'Balance'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')<=-1),0) 'Future'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=0 and DateDiff(day, T0.DueDate,'[%1]')<=30),0) 'Current'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>30 and DateDiff(day, T0.DueDate,'[%1]')<=60),0) '31-60 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>60 and DateDiff(day, T0.DueDate,'[%1]')<=90),0) '61-90 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>90 and DateDiff(day, T0.DueDate,'[%1]')<=120),0) '91-120 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=121),0) '121+ Days'
    FROM JDT1 T0 INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    WHERE (T0.MthDate IS NULL OR T0.MthDate > [%1]) AND T0.RefDate <= [%1] AND T1.CardType = 'C'
    ORDER BY T1.CardCode, T0.DueDate, T0.Ref1

  • How to write a SQL Query without using group by clause

    Hi,
    Can anyone help me to find out if there is a approach to build a SQL Query without using group by clause.
    Please site an example if is it so,
    Regards

    I hope this example could illuminate danepc on is problem.
    CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
    CREATE OR REPLACE FUNCTION GET_ARR return my_array
    as
         arr my_array;
    begin
         arr := my_array();
         for i in 1..10 loop
              arr.extend;
              arr(i) := i mod 7;
         end loop;
         return arr;
    end;
    select column_value
    from table(get_arr)
    order by column_value;
    select column_value,count(*) occurences
    from table(get_arr)
    group by column_value
    order by column_value;And the output should be something like this:
    SQL> CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
      2  /
    Tipo creato.
    SQL>
    SQL> CREATE OR REPLACE FUNCTION GET_ARR return my_array
      2  as
      3   arr my_array;
      4  begin
      5   arr := my_array();
      6   for i in 1..10 loop
      7    arr.extend;
      8    arr(i) := i mod 7;
      9   end loop;
    10   return arr;
    11  end;
    12  /
    Funzione creata.
    SQL>
    SQL>
    SQL> select column_value
      2  from table(get_arr)
      3  order by column_value;
    COLUMN_VALUE
               0
               1
               1
               2
               2
               3
               3
               4
               5
               6
    Selezionate 10 righe.
    SQL>
    SQL> select column_value,count(*) occurences
      2  from table(get_arr)
      3  group by column_value
      4  order by column_value;
    COLUMN_VALUE OCCURENCES
               0          1
               1          2
               2          2
               3          2
               4          1
               5          1
               6          1
    Selezionate 7 righe.
    SQL> Bye Alessandro

Maybe you are looking for

  • External Hard Drive - One Partition shows no files.

    I have an airport extreme with a WD 600 GB HD hooked up to the USB port. I have 2 partitions on the HD, the apple parition works fine (I am using it as my time capsule HD) The FAT32 partition shows up on the desktop and in the finder, but I can't see

  • How to use two BAPIs in webdynpro Applicaiton?

    Hi All, I'm developing one webdynpro application which is using BAPI_FLIGHT_GETLIST for gettting list of flights and then using an other bapi BAPI_FLIGHT_GETDETAIL for getting details of particular flight which is selected from getlist bapi. how can

  • Cast question

    * Local Function Prototypes */ myreturn xx_ioctl(dev_t, int, int, int, cred_t *, int *); <<(1) /* definition */ myreturn xx_ioctl(dev_t dev, int cmd, int arg, int flag, <<(2) cred_t cred_p, int rval_p) [snipped] (myfunc([snipped], (caddr_t)arg, [snip

  • OBIEE Data Modelling queries

    Hi, I am trying to create a data model for the OBIEE reporting from a source database. I have a fact table that looks like the below Fact-Key Customer_id Facility_id market_value_amt Coll_key Guar_key Derivative_key ==================================

  • Oracle SOAP

    Hi, Whenever we use Jdeveloper to create web service automatically, JDeveloper will include Oracle SOAP library. Is there any way to ask JDeveloper to use other SOAP library, eg. an open source SOAP library if there's one? Please advise. Thank you.