SQL query / Group by

Hello All,
i have the fallowing query:
SELECT dbo.OIGE.DocDate, dbo.OIGE.DocNum, dbo.IGE1.ItemCode, dbo.IGE1.Dscription, dbo.IGE1.Quantity, dbo.OITM.FrgnName, dbo.OITM.OnHand,
               dbo.OITM.IsCommited, dbo.OITM.OnOrder
FROM  dbo.OIGE INNER JOIN
               dbo.IGE1 ON dbo.OIGE.DocEntry = dbo.IGE1.DocEntry INNER JOIN
               dbo.OITM ON dbo.IGE1.ItemCode = dbo.OITM.ItemCode
and want to make a commulation of the Quantity per item code.
can you help me?
tahnk you and best regards
Serkan

Hello Serkan,
If you need one line per item, you have to omit first two fields.
Try this one to see:
SELECT T0.ItemCode, Max(T2.Dscription) 'Description', SUM(T2.Quantity) 'QTY', T0.FrgnName, T0.OnHand, T0.IsCommited, T0.OnOrder
FROM dbo.OIGE T1 INNER JOIN
dbo.IGE1 T2 ON T1.DocEntry = T2.DocEntry INNER JOIN
dbo.OITM T0 ON T2.ItemCode = T0.ItemCode
GROUP BY T0.ItemCode, T0.FrgnName, T0.OnHand, T0.IsCommited, T0.OnOrder
Thanks,
Gordon

Similar Messages

  • SQL query group by with concatenation

    How can i put the name of the column i concatenated in group by command?
    Example is:
    tbl_staff
    user_id     name          profile          last_name
    1     una          0001          astfirst
    2     pangalawa     0001          lastsecond
    3 pangatlo     0001          lastthird
    4 pangapat     0001          lastfourth
    5 panglima     0002          lastfifth
    tbl_work_assignment
    wa_id     handled_by     status
    10     1          active
    20     1          active
    30     2          closed
    40     3          active
    50     3          closed
    60     3          active
    If my Query is:
    select s.user_id, s.name, count(wa.wa_id)
    from tbl_staff s
    left join tbl_work_assignment wa
    on wa.handled_by = s.user_id
    where profile = '0001' and status = 'active'
    group by s.user_id, s.name
    I will get this result
    s.user_id     s.name          count(wa.wa_id)
    1          una          2
    3          pangatlo     2
    My question is:
    "HOW CAN I CONCATENATE THE 'NAME' AND 'LAST_NAME' COLUMNS AND PUT THEIR COLUMN NAME IN GROUP BY?"
    Desired Resultset is:
    s.user_id     s.name          full_name count(wa.wa_id)
    1          una          una lastfirst 2
    3          pangatlo     pangatlo lastthird 2
    I hope you understood my question.. I can explain further if its not clear. Thanks

    And the proof that Alex's last suggestion works:
    SQL> create table tbl_staff (user_id,name,profile,last_name)
      2  as
      3  select 1, 'una', '0001', 'astfirst' from dual union all
      4  select 2, 'pangalawa', '0001', 'lastsecond' from dual union all
      5  select 3, 'pangatlo', '0001', 'lastthird' from dual union all
      6  select 4, 'pangapat', '0001', 'lastfourth' from dual union all
      7  select 5, 'panglima', '0002', 'lastfifth' from dual
      8  /
    Tabel is aangemaakt.
    SQL> create table tbl_work_assignment (wa_id,handled_by,status)
      2  as
      3  select 10, 1, 'active' from dual union all
      4  select 20, 1, 'active' from dual union all
      5  select 30, 2, 'closed' from dual union all
      6  select 40, 3, 'active' from dual union all
      7  select 50, 3, 'closed' from dual union all
      8  select 60, 3, 'active' from dual
      9  /
    Tabel is aangemaakt.
    SQL> select s.user_id
      2       , s.name
      3       , s.name || ' ' || s.last_name full_name
      4       , count(wa.wa_id)
      5    from tbl_staff s
      6         left join tbl_work_assignment wa on wa.handled_by = s.user_id
      7   where profile = '0001'
      8     and status = 'active'
      9   group by s.user_id
    10       , s.name
    11       , s.last_name
    12  /
       USER_ID NAME      FULL_NAME            COUNT(WA.WA_ID)
             1 una       una astfirst                       2
             3 pangatlo  pangatlo lastthird                 2
    2 rijen zijn geselecteerd.Regards,
    Rob.

  • SQL Query Group By Issues - Urgent

    I currently have an issue writing a pl\sql report, I can get part of the way to the results I want but the group by clause is causing problems, because I have to add more columns to the group by, dispersing the figures further, I have tried it with coalesce for each of the task types but I still get the same results, I am getting close to the results I need but not quite there yet. I would really appreciate it if someone could take at look at this for me as it is an urgent requirement.
    The report is based on the tables similar to the following:
    TASKS, ORGANISATIONS, POSITIONS
    A position is a member of an organisation.
    A task has a position assigned to it.
    The SQL for the tables and to insert the data that would produce the report is detailed below:
    CREATE TABLE TASKS
    (     TASK_ID NUMBER NOT NULL ENABLE,
         TASK_TYPE VARCHAR2 (15 BYTE) NOT NULL ENABLE,
         STATUS VARCHAR2 (15 BYTE) NOT NULL ENABLE,
         POS_ID NUMBER NOT NULL ENABLE,
         CONSTRAINT TASKS_PK PRIMARY KEY (TASK_ID));
    CREATE TABLE ORGANISATIONS
    (     ORG_ID NUMBER NOT NULL ENABLE,
         ORG_NAME VARCHAR2 (15 BYTE) NOT NULL ENABLE,
         CONSTRAINT ORGANISATIONS_PK PRIMARY KEY (ORG_ID));
    CREATE TABLE POSITIONS
    (     POS_ID NUMBER NOT NULL ENABLE,
         POS_NAME VARCHAR2 (25 BYTE) NOT NULL ENABLE,
         ORG_ID NUMBER NOT NULL ENABLE,
         CONSTRAINT POSITIONS_PK PRIMARY KEY (POS_ID));
    INSERT INTO ORGANISATIONS (ORG_ID, ORG_NAME) VALUES (1,'ABC');
    INSERT INTO ORGANISATIONS (ORG_ID, ORG_NAME) VALUES (2,'DEF');
    INSERT INTO ORGANISATIONS (ORG_ID, ORG_NAME) VALUES (3,'EFG');
    INSERT INTO POSITIONS (POS_ID, POS_NAME, ORG_ID) VALUES (1,'ABC-1', 1);
    INSERT INTO POSITIONS (POS_ID, POS_NAME, ORG_ID) VALUES (3,'ABC-2', 1);
    INSERT INTO POSITIONS (POS_ID, POS_NAME, ORG_ID) VALUES (2,'ABC-3', 1);
    INSERT INTO POSITIONS (POS_ID, POS_NAME, ORG_ID) VALUES (5,'DEF-2', 2);
    INSERT INTO POSITIONS (POS_ID, POS_NAME, ORG_ID) VALUES (4,'DEF-1', 2);
    INSERT INTO POSITIONS (POS_ID, POS_NAME, ORG_ID) VALUES (7,'EFG-1', 3);
    INSERT INTO TASKS (TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (12,'TASK_TYPE_3','LIVE',3);
    INSERT INTO TASKS (TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (11,'TASK_TYPE_2','LIVE',3);
    INSERT INTO TASKS (TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (10,'TASK_TYPE_2','LIVE',2);
    INSERT INTO TASKS (TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (9,'TASK_TYPE_2','LIVE',2);
    INSERT INTO TASKS (TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (8,'TASK_TYPE_1','LIVE',3);
    INSERT INTO TASKS (TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (7,'TASK_TYPE_1','LIVE',3);
    INSERT INTO TASKS (TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (6,'TASK_TYPE_1','LIVE',3);
    INSERT INTO TASKS (TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (5,'TASK_TYPE_1','LIVE',3);
    INSERT INTO TASKS (TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (4,'TASK_TYPE_1','LIVE',2);
    INSERT INTO TASKS (TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (3,'TASK_TYPE_3','LIVE',1);
    INSERT INTO TASKS (TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (2,'TASK_TYPE_1','LIVE',1);
    INSERT INTO TASKS (TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (1,'TASK_TYPE_1','LIVE',1);
    INSERT INTO TASKS (TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (13,'TASK_TYPE_3','LIVE',3);
    The report should detail the following information based on the information in the tables:
    1st Column
    Organisation
    ABC
    DEF
    EFG
    2nd Column
    No. of Positions in Organsiation
    3
    2
    1
    With total of the number of people in all of the organisation 6
    3rd Column
    Number of tasks assigned to the organisation of task type1
    2
    1
    4
    4th Column
    Number of tasks assigned to the organisation of task type 2
    0
    2
    1
    5th Column
    Number of tasks assigned to the organisation of task type 3
    1
    0
    2
    Total no of tasks assigned to the Organisation
    3
    3
    7
    Message was edited by:
    Suzy_r_82
    Message was edited by:
    Suzy_r_82

    Hi,
    Apologies, my insert statements where incorrect, if you try the data below instead it should give you output I was expecting
    INSERT INTO TASKS( TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (1,'TASK_TYPE_1', 'LIVE',1);
    INSERT INTO TASKS( TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (2,'TASK_TYPE_1', 'LIVE',2);
    INSERT INTO TASKS( TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (3,'TASK_TYPE_1', 'LIVE',5);
    INSERT INTO TASKS( TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (4,'TASK_TYPE_1', 'LIVE',7);
    INSERT INTO TASKS( TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (5,'TASK_TYPE_1', 'LIVE',7);
    INSERT INTO TASKS( TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (6,'TASK_TYPE_1', 'LIVE',7);
    INSERT INTO TASKS( TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (7,'TASK_TYPE_1', 'LIVE',7);
    INSERT INTO TASKS( TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (8,'TASK_TYPE_2', 'LIVE',4);
    INSERT INTO TASKS( TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (9,'TASK_TYPE_2', 'LIVE',5);
    INSERT INTO TASKS( TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (10,'TASK_TYPE_3', 'LIVE',1);
    INSERT INTO TASKS( TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (11,'TASK_TYPE_3', 'LIVE',7);
    INSERT INTO TASKS( TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (12,'TASK_TYPE_2', 'LIVE',7);
    INSERT INTO TASKS( TASK_ID, TASK_TYPE, STATUS, POS_ID) VALUES (13,'TASK_TYPE_3', 'LIVE',7);
    The results I would like are
    ORG    No. of Pos     No of Task    No of Task     No of Task     Total no
               In Org           Type1 for      Type2 for        Type3 for       of Tasks
                                   Org             Org                Org               for Org
    ABC        3                   2                 0                   1                   3
    DEF        2                   1                 2                   0                   3
    EFG        1                   4                 1                   2                   7
    Total        6The results I get are multiple lines for each organisation, I would like to rollup these lines so I can have one line per organisation.
    Hope this helps a bit more, I appreciate the help, let me know if you need more information
    Thanks
    Suzy

  • SQL Query, group by or self join?

    Hi All,
    I have a table with about 100,000 rows.. It is a linking table. I want to filter out some of the data. At the bottom I will put a sample table. I am really after advice if I should be using the group by, or something else. It is really slow, and I really wanted to make a view from the query, but it won't run in realtime (I thought about Materialised views, but the data could change and I would want it updated)
    So the data would like like this.
    1 1
    A 1
    B 1
    1 A
    1 B
    2 null/0
    And I want to transform it into a result that looks like this.
    A 1
    B 1
    2 0
    (I can live with 1 1 as well)
    The first query I have come up with is
    select
    A.TXN, A.ID SCHED_INFO, A.STA ORIG_ACT
    from
    SELECT
    Txn, ID,
    STA
    FROM TEST_STA
    WHERE TXN < 0
    ) A,
    select ID, count(STA)
    FROM test_STA
    WHERE TXN < 0
    group by ID
    HAVING count(STA) > 1
    ) B
    where A.ID = B.ID
    OR A.STA = '0'
    The second I came up with was.
    select B.Id , A.id STA
    from test_STA A, test_STA B
    where A.STA = '0'
    AND B.STA != '0'
    AND B.STA = A.ID
    AND b.TXN < 0
    Where the data looks like
    create table test_STA
    ( TXN NUMBER,
    ID VARCHAR2(20),
    STA VARCHAR2(20) )
    insert into test_STA Values (1, '1', '0')
    insert into test_STA Values (-1, '1', '1')
    insert into test_STA Values (-1, '1', 'A')
    insert into test_STA Values (-1, '1', 'B')
    insert into test_STA Values (-1, 'A', '1')
    insert into test_STA Values (-1, 'B', '1')
    insert into test_STA Values (-1, '2', '0')
    TXN is the transaction number -1 is current, others (> 0 are old)
    What does all this mean..
    Well
    1 is a parent, with A and B as children.
    2 is a parent with no children.
    So what I want to do return is Parents with no children, and children but not their parents..
    So which path should I continue my efforts down do you think ? The first one, with the group by, or the second one, with the join to it's self.
    Paul

    Hi,
    If you can guarantee, that every child has also a record then following query returns your result:
    select ID, count(*)
    from test_STA
    group by ID
    having count(*) = 1
    ID COUNT(*)
    2     1
    A     1
    B     1

  • Using a SQL Query Group by is needed

    Hi All,
    Scenario Below:
    we have 2 Transactions, 5 Lines and each line is having 2 Taxes correspondingly. We have few more formula columns which are calculating based on requirements.
    We need to Group the amount at Line level for the one specific TAX.
    say: L1 1, L2 2, L3 3, L4 4, L5 5. for one tax having L1, L2 and L3 which needs to be sum up 6
    and for other tax needs to sum up to 9.
    But, we need to display all the Lines.
    Regards,
    Reddy.

    Hi, Reddy,
    Use the analytic SUM function instead of the aggregate function if you don't want to get only one line of output per group.
    Since I don't have a copy of your table, I'll use the scott.emp table to illustrate.
    The following query gets some information about individual employees, along with the total salary of all the employees with the same job:
    SELECT       job
    ,       ename
    ,       sal
    ,       SUM (sal) OVER (PARTITION BY  job)     AS total_sal
    FROM       scott.emp
    ORDER BY  job
    ;Output:
    JOB       ENAME             SAL  TOTAL_SAL
    ANALYST   SCOTT            3000       6000
    ANALYST   FORD             3000       6000
    CLERK     MILLER           1300       4150
    CLERK     JAMES             950       4150
    CLERK     SMITH             800       4150
    CLERK     ADAMS            1100       4150
    MANAGER   BLAKE            2850       8275
    MANAGER   JONES            2975       8275
    MANAGER   CLARK            2450       8275
    PRESIDENT KING             5000       5000
    SALESMAN  TURNER           1500       5600
    SALESMAN  MARTIN           1250       5600
    SALESMAN  WARD             1250       5600
    SALESMAN  ALLEN            1600       5600Almost all of the aggregate functions (including SUM, AVG, COUNT, MIN, even user-defined aggregate functions like STRAGG) have analytic counterparts. The keyword OVER after the argument list marks the function as analytic.
    The analytic PARTITION BY clause corresponds to the aggregate GROUP BY.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements) and the results you want from that data.
    It never hurts to say what version of Oracle you're using.

  • Issue in creation of group in oim database through sql query.

    hi guys,
    i am trying to create a group in oim database through sql query:
    insert into ugp(ugp_key,ugp_name,ugp_create,ugp_update,ugp_createby,ugp_updateby,)values(786,'dbrole','09-jul-12','09-jul-12',1,1);
    it is inserting the group in ugp table but it is not showing in admin console.
    After that i also tried with this query:
    insert into gpp(ugp_key,gpp_ugp_key,gpp_write,gpp_delete,gpp_create,gpp_createby,gpp_update,gpp_updateby)values(786,1,1,1,'09-jul-12',1,'09-jul-12',1);
    After that i tried with this query.but still no use.
    and i also tried to assign a user to the group through query:
    insert into usg(ugp_key,usr_key,usg_priority,usg_create,usg_update,usg_createby,usg_updateby)values(4,81,1,'09-jul-12','09-jul-12',1,1);
    But still the same problem.it is inserting in db.but not listing in admin console.
    thanks,
    hanuman.

    Hanuman Thota wrote:
    hi vladimir,
    i didn't find this 'ugp_seq'.is this a table or column?where is it?
    It is a sequence.
    See here for details on oracle sequences:
    http://www.techonthenet.com/oracle/sequences.php
    Most of the OIM database schema is created with the following script, located in the RCU distribution:
    $RCU_HOME/rcu/integration/oim/sql/xell.sql
    there you'll find plenty of sequence creation directives like:
    create sequence UGP_SEQ
    increment by 1
    start with 1
    cache 20
    to create a sequence, and
    INSERT INTO UGP (UGP_KEY, UGP_NAME, UGP_UPDATEBY, UGP_UPDATE, UGP_CREATEBY, UGP_CREATE,UGP_ROWVER, UGP_DATA_LEVEL, UGP_ROLE_CATEGORY_KEY, UGP_ROLE_OWNER_KEY, UGP_DISPLAY_NAME, UGP_ROLENAME, UGP_DESCRIPTION, UGP_NAMESPACE)
    VALUES (ugp_seq.nextval,'SYSTEM ADMINISTRATORS', sysadmUsrKey , SYSDATE,sysadmUsrKey , SYSDATE, hextoraw('0000000000000000'), 1, roleCategoryKey, sysadmUsrKey, 'SYSTEM ADMINISTRATORS', 'SYSTEM ADMINISTRATORS', 'System Administrator role for OIM', 'Default');
    as a sequence usage example.
    Regards,
    Vladimir

  • 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

  • Displaying a radio group in SQL QUERY report region

    Good morning everyone,
    I have a report in which a column - ORDER STATUS, will come in with a value of 1, 2 or 3...being order unfilled, order partially filled, or order filled, respectively.
    I would like to display the order status as a radio group on the report so that it will be easy to run down the column of radio buttons to see what is filled, etc.
    I've gone to the manual and checked the doco on HTMLDB_ITEM.RADIOGROUP. But the example given there is actually for CHECKBOX (is this an error?!?).
    I went to the forums and found nothing suitable.
    My region is an SQL QUERY. Can I display the STATUS as a radio group in the SELECT ?
    This is the question.
    Thankyou in anticipation. TC. 23/11/2004

    Tony,
    There may be better solutions, but here's what I was thinking:    create table orders (id number, status number, customer varchar(30))
        insert into orders (id,status,customer) values(1,1,'ACME')
        insert into orders (id,status,customer) values(2,2,'BENSON')
        insert into orders (id,status,customer) values(3,3,'CLARKE')
        commit
        Query Source
        select
          id "ORDER NUMBER",
          decode(status,
            1,htmldb_item.RADIOGROUP(1,status,'1','unfilled')||htmldb_item.RADIOGROUP(2,status,'2','partial','"disabled=true"')||htmldb_item.RADIOGROUP(3,status,'3','filled','"disabled=true"'),
            2,htmldb_item.RADIOGROUP(1,status,'1','unfilled','"disabled=true"')||htmldb_item.RADIOGROUP(2,status,'2','partial')||htmldb_item.RADIOGROUP(3,status,'3','filled','"disabled=true"'),
            3,htmldb_item.RADIOGROUP(1,status,'1','unfilled','"disabled=true"')||htmldb_item.RADIOGROUP(2,status,'2','partial','"disabled=true"')||htmldb_item.RADIOGROUP(3,status,'3','filled'))
          "STATUS",
          customer "Customer Name"
        from orders;Scott

  • SQL Query for mapping a set of batches to a class rooms group

    Hi All,
    I am using Oracle 11g Release 2 database.
    I have the following data set:
    ClassRooms
    ClassId ClassName                    Capacity     Group
    1 Babbage/Software Engg Lab          24          1
    2     Basement - PG Block               63          1
    3     Classroom 1                    56          1
    4     Classroom 10                    24          1
    5     Classroom 11                    24          1
    6     Classroom 12                    35          1
    7     Classroom 13                    42          1
    8     Classroom 14                    42          1
    9     Classroom 15                    42          1
    10     Classroom 2                    35          1
    11     Classroom 3                    35          1
    12     Classroom 4                     35          1
    13     Classroom 5                    35          1
    14     Classroom 6                    25          1
    15     Classroom 7                    25          1
    16     Classroom 8                    24          1
    17     Classroom 9                    24          1
    18     Control Sys Lab                    24          1
    19     Dig & Embd Sys Lab               20          1
    20     DSP & Comm Lab                    20          1
    21     Electromechanical System Lab     28          1
    22     Farabi/Web Tech Lab               36          1
    23     Gen Purpose Lab                    40          1
    24     Shirazi/DB Tech Lab               36          1
    25     Adv Elect Lab                    30          2
    26     Classroom 16                    42          2
    27     Classroom 17                    49          2
    28     Classroom 18                    56          2
    29     Classroom 19                    42          2
    30     Classroom 20                    49          2
    31     Classroom 21                    35          3
    32     Classroom 22                    35          3
    33     MDA Lab                         20          3
    DegreeBatches
    BatchId      BatchName Strength
    1          BIT-11          79          
    2          BIT-12          28          
    3          BS(CS)-1          35          
    4          BS(CS)-2          78          
    5          BE(SE)-1          69          
    6          BE(SE)-2          84          
    7          BE(SE)-3          64          
    8          BICSE-7          84          
    9          BICSE-8          43          
    10          BEE-1          112          
    11          BEE-2          151          
    12          BEE-3          157          
    13          BEE-4          157          
    I want to map a degree batch combination to a class rooms group in such away that they fully utilize maximum capacity of the class rooms within a group (Ideal case) or as close to it as possible. Can it be done with a SQL query?
    Any response will be highly appreciated.
    SQL Scripts to generate the required tables and populate data is below:
    CREATE TABLE ClassRooms (ClassId NUMBER, ClassName     VARCHAR2(50), Capacity NUMBER, Group NUMBER);
    INSERT INTO ClassRooms VALUES(1,'Babbage/Software Engg Lab',24,1);
    INSERT INTO ClassRooms VALUES(2,'Basement - PG Block',63,1);
    INSERT INTO ClassRooms VALUES(3,'Classroom 1',56,1);
    INSERT INTO ClassRooms VALUES(4,'Classroom 10',24,1);
    INSERT INTO ClassRooms VALUES(5,'Classroom 11',24,1);
    INSERT INTO ClassRooms VALUES(6,'Classroom 12',35,1);
    INSERT INTO ClassRooms VALUES(7,'Classroom 13',42,1);
    INSERT INTO ClassRooms VALUES(8,'Classroom 14',42,1);
    INSERT INTO ClassRooms VALUES(9,'Classroom 15',42,1);
    INSERT INTO ClassRooms VALUES(10,'Classroom 2',35,1);
    INSERT INTO ClassRooms VALUES(11,'Classroom 3',35,1);
    INSERT INTO ClassRooms VALUES(12,'Classroom 4',35,1);
    INSERT INTO ClassRooms VALUES(13,'Classroom 5',35,1);
    INSERT INTO ClassRooms VALUES(14,'Classroom 6',25,1);
    INSERT INTO ClassRooms VALUES(15,'Classroom 7',25,1);
    INSERT INTO ClassRooms VALUES(16,'Classroom 8',24,1);
    INSERT INTO ClassRooms VALUES(17,'Classroom 9',24,1);
    INSERT INTO ClassRooms VALUES(18,'Control Sys Lab',24,1);
    INSERT INTO ClassRooms VALUES(19,'Dig & Embd Sys Lab',20,1);
    INSERT INTO ClassRooms VALUES(20,'DSP & Comm Lab',20,1);
    INSERT INTO ClassRooms VALUES(21,'Electromechanical System Lab',28,1);
    INSERT INTO ClassRooms VALUES(22,'Farabi/Web Tech Lab',36,1);
    INSERT INTO ClassRooms VALUES(23,'Gen Purpose Lab',40,1);
    INSERT INTO ClassRooms VALUES(24,'Shirazi/DB Tech Lab',36,1);
    INSERT INTO ClassRooms VALUES(25,'Adv Elect Lab',30,2);
    INSERT INTO ClassRooms VALUES(26,'Classroom 16',42,2);
    INSERT INTO ClassRooms VALUES(27,'Classroom 17',49,2);
    INSERT INTO ClassRooms VALUES(28,'Classroom 18',56,2);
    INSERT INTO ClassRooms VALUES(29,'Classroom 19',42,2);
    INSERT INTO ClassRooms VALUES(30,'Classroom 20',49,2);
    INSERT INTO ClassRooms VALUES(31,'Classroom 21',35,3);
    INSERT INTO ClassRooms VALUES(32,'Classroom 22',35,3);
    INSERT INTO ClassRooms VALUES(33,'MDA Lab',20,3);
    CREATE TABLE DegreeBatches (BatchId NUMBER, BatchName VARCHAR2(50), Strength NUMBER);
    INSERT INTO DegreeBatches VALUES(1,'BIT-11',79);          
    INSERT INTO DegreeBatches VALUES(2,'BIT-12',28);          
    INSERT INTO DegreeBatches VALUES(3,'BS(CS)-1',35);          
    INSERT INTO DegreeBatches VALUES(4,'BS(CS)-2',78);          
    INSERT INTO DegreeBatches VALUES(5,'BE(SE)-1',69);          
    INSERT INTO DegreeBatches VALUES(6,'BE(SE)-2',84);          
    INSERT INTO DegreeBatches VALUES(7,'BE(SE)-3',64);          
    INSERT INTO DegreeBatches VALUES(8,'BICSE-7',84);          
    INSERT INTO DegreeBatches VALUES(9,'BICSE-8',43);          
    INSERT INTO DegreeBatches VALUES(10,'BEE-1',112);          
    INSERT INTO DegreeBatches VALUES(11,'BEE-2',151);     
    INSERT INTO DegreeBatches VALUES(12,'BEE-3',157);     
    INSERT INTO DegreeBatches VALUES(13,'BEE-4',157);     
    Best Regards
    Bilal
    Edited by: Bilal on 27-Dec-2012 09:52
    Edited by: Bilal on 27-Dec-2012 10:07

    Bilal, thanks for the nice problem! Another possibility for duplicate checking is to write a small PL/SQL function returning 1 if a duplicate id is found, then equate it to 0: 'Duplicate_Token_Found (p_str_main VARCHAR2, p_str_trial VARCHAR2) RETURN NUMBER'. This would parse the second string and might use p_str_main LIKE '%,' || l_id || ',%' for each id. Anyway the full query (without that) is given below:
    Solution with names
    SQL> WITH rsf_itm (con_id, max_weight, nxt_id, lev, tot_weight, tot_profit, path, root_id, lev_1_id) AS (
      2  SELECT c.id,
      3         c.max_weight,
      4         i.id,
      5         0,
      6         i.item_weight,
      7         i.item_profit,
      8         ',' || i.id || ',',
      9         i.id,
    10         0
    11    FROM items i
    12   CROSS JOIN containers c
    13   UNION ALL
    14  SELECT r.con_id,
    15         r.max_weight,
    16         i.id,
    17         r.lev + 1,
    18         r.tot_weight + i.item_weight,
    19         r.tot_profit + i.item_profit,
    20         r.path || i.id || ',',
    21         r.root_id,
    22         CASE WHEN r.lev = 0 THEN i.id ELSE r.nxt_id END
    23    FROM rsf_itm r
    24    JOIN items i
    25      ON i.id > r.nxt_id
    26     AND r.tot_weight + i.item_weight <= r.max_weight
    27   ORDER BY 1, 2
    28  ) SEARCH DEPTH FIRST BY nxt_id SET line_no
    29  , rsf_con (nxt_con_id, nxt_line_no, con_path, itm_path, tot_weight, tot_profit, lev) AS (
    30  SELECT con_id,
    31         line_no,
    32         To_Char(con_id),
    33         ':' || con_id || '-' || (lev + 1) || ':' || path,
    34         tot_weight,
    35         tot_profit,
    36         0
    37    FROM rsf_itm
    38   UNION ALL
    39  SELECT r_i.con_id,
    40         r_i.line_no,
    41         r_c.con_path || ',' || r_i.con_id,
    42         r_c.itm_path ||  ':' || r_i.con_id || '-' || (r_i.lev + 1) || ':' || r_i.path,
    43         r_c.tot_weight + r_i.tot_weight,
    44         r_c.tot_profit + r_i.tot_profit,
    45         r_c.lev + 1
    46    FROM rsf_con r_c
    47    JOIN rsf_itm r_i
    48      ON r_i.con_id > r_c.nxt_con_id
    49   WHERE r_c.itm_path NOT LIKE '%,' || r_i.root_id || ',%'
    50     AND r_c.itm_path NOT LIKE '%,' || r_i.lev_1_id || ',%'
    51     AND r_c.itm_path NOT LIKE '%,' || r_i.nxt_id || ',%'
    52  )
    53  , paths_ranked AS (
    54  SELECT itm_path || ':' itm_path, tot_weight, tot_profit, lev + 1 n_cons,
    55         Rank () OVER (ORDER BY tot_profit DESC) rnk,
    56         Row_Number () OVER (ORDER BY tot_profit DESC) sol_id
    57    FROM rsf_con
    58  ), best_paths AS (
    59  SELECT itm_path, tot_weight, tot_profit, n_cons, sol_id
    60    FROM paths_ranked
    61   WHERE rnk = 1
    62  ), row_gen AS (
    63  SELECT LEVEL lev
    64    FROM DUAL
    65  CONNECT BY LEVEL <= (SELECT Count(*) FROM items)
    66  ), con_v AS (
    67  SELECT  b.itm_path, r.lev con_ind, b.sol_id, b.tot_weight, b.tot_profit,
    68          Substr (b.itm_path, Instr (b.itm_path, ':', 1, 2*r.lev - 1) + 1,
    69            Instr (b.itm_path, ':', 1, 2*r.lev) - Instr (b.itm_path, ':', 1, 2*r.lev - 1) - 1)
    70             con_nit_id,
    71          Substr (b.itm_path, Instr (b.itm_path, ':', 1, 2*r.lev) + 1,
    72            Instr (b.itm_path, ':', 1, 2*r.lev + 1) - Instr (b.itm_path, ':', 1, 2*r.lev) - 1)
    73             itm_str
    74    FROM best_paths b
    75    JOIN row_gen r
    76      ON r.lev <= b.n_cons
    77  ), con_split AS (
    78  SELECT itm_path, con_ind, sol_id, tot_weight, tot_profit,
    79         Substr (con_nit_id, 1, Instr (con_nit_id, '-', 1) - 1) con_id,
    80         Substr (con_nit_id, Instr (con_nit_id, '-', 1) + 1) n_items,
    81         itm_str
    82    FROM con_v
    83  ), itm_v AS (
    84  SELECT  c.itm_path, c.con_ind, c.sol_id, c.con_id, c.tot_weight, c.tot_profit,
    85          Substr (c.itm_str, Instr (c.itm_str, ',', 1, r.lev) + 1,
    86            Instr (c.itm_str, ',', 1, r.lev + 1) - Instr (c.itm_str, ',', 1, r.lev) - 1)
    87             itm_id
    88    FROM con_split c
    89    JOIN row_gen r
    90      ON r.lev <= c.n_items
    91  )
    92  SELECT v.sol_id,
    93         v.tot_weight s_wt, v.tot_profit s_pr, c.id c_id, c.name c_name, c.max_weight m_wt,
    94         Sum (i.item_weight) OVER (PARTITION BY v.sol_id, c.id) c_wt,
    95         i.id i_id, i.name i_name, i.item_weight i_wt, i.item_profit i_pr
    96    FROM itm_v v
    97    JOIN containers c
    98      ON c.id = To_Number (v.con_id)
    99    JOIN items i
    100      ON i.id = To_Number (v.itm_id)
    101   ORDER BY sol_id, con_id, itm_id
    102  /
        SOL_ID S_WT S_PR  C_ID C_NAME          M_WT C_WT  I_ID I_NAME     I_WT I_PR
             1  255  255     1 SEECS UG Block   100  100     1 BIT-10       35   35
                                                             2 BIT-11       40   40
                                                             6 BICSE-7      25   25
                             2 IAEC Building     70   70     4 BSCS-3       40   40
                                                             7 BESE-3       30   30
                             3 RIMMS Building    90   85     3 BSCS-2       35   35
                                                             5 BEE-4        50   50
             2  255  255     1 SEECS UG Block   100   95     4 BSCS-3       40   40
                                                             6 BICSE-7      25   25
                                                             7 BESE-3       30   30
                             2 IAEC Building     70   70     1 BIT-10       35   35
                                                             3 BSCS-2       35   35
                             3 RIMMS Building    90   90     2 BIT-11       40   40
                                                             5 BEE-4        50   50
             3  255  255     1 SEECS UG Block   100  100     3 BSCS-2       35   35
                                                             4 BSCS-3       40   40
                                                             6 BICSE-7      25   25
                             2 IAEC Building     70   65     1 BIT-10       35   35
                                                             7 BESE-3       30   30
                             3 RIMMS Building    90   90     2 BIT-11       40   40
                                                             5 BEE-4        50   50
             4  255  255     1 SEECS UG Block   100  100     3 BSCS-2       35   35
                                                             4 BSCS-3       40   40
                                                             6 BICSE-7      25   25
                             2 IAEC Building     70   70     2 BIT-11       40   40
                                                             7 BESE-3       30   30
                             3 RIMMS Building    90   85     1 BIT-10       35   35
                                                             5 BEE-4        50   50
             5  255  255     1 SEECS UG Block   100   95     2 BIT-11       40   40
                                                             6 BICSE-7      25   25
                                                             7 BESE-3       30   30
                             2 IAEC Building     70   70     1 BIT-10       35   35
                                                             3 BSCS-2       35   35
                             3 RIMMS Building    90   90     4 BSCS-3       40   40
                                                             5 BEE-4        50   50
             6  255  255     1 SEECS UG Block   100  100     2 BIT-11       40   40
                                                             3 BSCS-2       35   35
                                                             6 BICSE-7      25   25
                             2 IAEC Building     70   65     1 BIT-10       35   35
                                                             7 BESE-3       30   30
                             3 RIMMS Building    90   90     4 BSCS-3       40   40
                                                             5 BEE-4        50   50
             7  255  255     1 SEECS UG Block   100  100     2 BIT-11       40   40
                                                             3 BSCS-2       35   35
                                                             6 BICSE-7      25   25
                             2 IAEC Building     70   70     4 BSCS-3       40   40
                                                             7 BESE-3       30   30
                             3 RIMMS Building    90   85     1 BIT-10       35   35
                                                             5 BEE-4        50   50
             8  255  255     1 SEECS UG Block   100  100     1 BIT-10       35   35
                                                             4 BSCS-3       40   40
                                                             6 BICSE-7      25   25
                             2 IAEC Building     70   70     2 BIT-11       40   40
                                                             7 BESE-3       30   30
                             3 RIMMS Building    90   85     3 BSCS-2       35   35
                                                             5 BEE-4        50   50
             9  255  255     1 SEECS UG Block   100  100     1 BIT-10       35   35
                                                             4 BSCS-3       40   40
                                                             6 BICSE-7      25   25
                             2 IAEC Building     70   65     3 BSCS-2       35   35
                                                             7 BESE-3       30   30
                             3 RIMMS Building    90   90     2 BIT-11       40   40
                                                             5 BEE-4        50   50
            10  255  255     1 SEECS UG Block   100  100     1 BIT-10       35   35
                                                             3 BSCS-2       35   35
                                                             7 BESE-3       30   30
                             2 IAEC Building     70   65     2 BIT-11       40   40
                                                             6 BICSE-7      25   25
                             3 RIMMS Building    90   90     4 BSCS-3       40   40
                                                             5 BEE-4        50   50
            11  255  255     1 SEECS UG Block   100  100     1 BIT-10       35   35
                                                             3 BSCS-2       35   35
                                                             7 BESE-3       30   30
                             2 IAEC Building     70   65     4 BSCS-3       40   40
                                                             6 BICSE-7      25   25
                             3 RIMMS Building    90   90     2 BIT-11       40   40
                                                             5 BEE-4        50   50
            12  255  255     1 SEECS UG Block   100   95     1 BIT-10       35   35
                                                             3 BSCS-2       35   35
                                                             6 BICSE-7      25   25
                             2 IAEC Building     70   70     2 BIT-11       40   40
                                                             7 BESE-3       30   30
                             3 RIMMS Building    90   90     4 BSCS-3       40   40
                                                             5 BEE-4        50   50
            13  255  255     1 SEECS UG Block   100   95     1 BIT-10       35   35
                                                             3 BSCS-2       35   35
                                                             6 BICSE-7      25   25
                             2 IAEC Building     70   70     4 BSCS-3       40   40
                                                             7 BESE-3       30   30
                             3 RIMMS Building    90   90     2 BIT-11       40   40
                                                             5 BEE-4        50   50
            14  255  255     1 SEECS UG Block   100  100     1 BIT-10       35   35
                                                             2 BIT-11       40   40
                                                             6 BICSE-7      25   25
                             2 IAEC Building     70   65     3 BSCS-2       35   35
                                                             7 BESE-3       30   30
                             3 RIMMS Building    90   90     4 BSCS-3       40   40
                                                             5 BEE-4        50   50
    98 rows selected.
    Elapsed: 00:00:01.42Edited by: BrendanP on 20-Jan-2013 11:25
    I found the regex needed to deduplicate:
    AND RegExp_Instr (r_c.itm_path || r_i.path, ',(\d+),.*?,\1,') = 0

  • SQL query using Group by and Aggregate function

    Hi All,
    I need your help in writing an SQL query to achieve the following.
    Scenario:
    I have table with 3 Columns. There are 3 possible values for col3 - Success, Failure & Error.
    Now I need a query which can give me the summary counts for distinct values of col3 for each GROUP BY of col1 and col2 values. When there are no values for col3 then it should return ZERO count.
    Example Data:
    Col1 Col2 Col3
    abc 01 success
    abc 02 success
    abc 01 success
    abc 01 Failure
    abc 01 Error
    abc 02 Failure
    abc 03 Error
    xyz 07 Failure
    Required Output:
    c1 c2 s_cnt F_cnt E_cnt (Heading)
    abc 01 2 1 1
    abc 02 1 1 0
    abc 03 0 0 1
    xyz 07 0 1 0
    s_cnt = Success count; F_cnt = Failure count; E_cnt = Error count
    Please note that the output should have 5 columns with col1, col2, group by (col1,col2)count(success), group by (col1,col2)count(failure), group by (col1,col2)count(error)
    and where ever there are NO ROWS then it should return ZERO.
    Thanks in advance.
    Regards,
    Shiva

    Hi,
    user13015050 wrote:
    Thanks TTT. Unfortunately I cannot use this solution because I have huge data for this.T's solution is basically the same as mine. The first 23 lines just simulates your table. Since you actually have a table, you would start with T's line 24:
    SELECT col1 c1, col2 c2, SUM(decode(col3, 'success', 1, 0)) s_cnt, ...
    user13015050 wrote:Thanks a lot Frank. It helped me out. I just did some changes to this as below and have no issues.
    SELECT     col1
    ,     col2
    ,     COUNT ( CASE
              WHEN col3 = 'SUCCESS'
              THEN 1
              END
         )          AS s_cnt
    ,     COUNT ( CASE
              WHEN col3 = 'FAILED'
              THEN 1
              END
         )          AS f_cnt
    ,     COUNT ( CASE
              WHEN col3 = 'ERROR'
              THEN 1
              END
         )          AS e_cnt
    FROM     t1
    WHERE c2 in ('PURCHASE','REFUND')
    and c4 between to_date('20091031000000','YYYYMMDDHH24MISS') AND to_date('20100131235959','YYYYMMDDHH24MISS')
    GROUP BY c1, c2
    ORDER BY c1, c2;
    Please let me know if you see any issues in this query.It's very hard to read.
    This site normally compresses spaces. Whenever you post formatted text (such as queries or results) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    Also, post exactly what you're using.  The code above is SELECTing col1 and col2, but there's no mention of either in the GROUP BY clause, so I don't believe it's really what you're using.
    Other than that, I don't see anything wrong or suspicious in the query.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • SQL Query - Mapping Groups to Batches

    I am using Oracle 11g Release 2.
    I have the following dataset:
    CREATE TABLE RoomGroups
    (group_id NUMBER,
    group_name VARCHAR2(30),
    group_capacity NUMBER);
    INSERT INTO RoomGroups VALUES(1, 'SEECS UG Block', 100);
    INSERT INTO RoomGroups VALUES(2, 'IAEC Building', 70);
    INSERT INTO RoomGroups VALUES(3, 'RIMMS Building', 90);
    Commit;
    CREATE TABLE DegreeBatches
    (batch_id NUMBER, batch_name VARCHAR2(30), batch_strength NUMBER);
    INSERT INTO DegreeBatches VALUES(10,'BIT-10',35);
    INSERT INTO DegreeBatches VALUES(20,'BIT-11',40);
    INSERT INTO DegreeBatches VALUES(30,'BSCS-2',35);
    INSERT INTO DegreeBatches VALUES(40,'BSCS-3',40);
    INSERT INTO DegreeBatches VALUES(50,'BEE-4',50);
    INSERT INTO DegreeBatches VALUES(60,'BICSE-7',25);
    INSERT INTO DegreeBatches VALUES(70,'BESE-3',30);
    Commit;
    I want to achieve the following thr single or multiple SQL queries:
    Firstly, get all possible sets of DegreeBatches for each group - in such a way that for each set the SUM(batch_strength) <= Capacity of that group as show below.
    GroupId     Batches     StrengthStr     StrengthTotal     Capacity
    1.     {BIT-10, BIT-11, BICSE-7}     {35, 40, 25}     100     100
    1.     {BSCS-2, BSCS-3, BICSE-7}     {35, 40, 25}     100     100
    1.     {BEE-4, BSCS-3}     {50, 40}     90     100
    2.     {BIT-10, BSCS-2}     {35, 35}     70     70
    2.     {BSCS-3, BESE-3}     {40, 30}     70     70
    2.     {BIT-11, BICSE-7}     {40, 25}     65     70
    and so on...
    Secondly, I want to retrieve only non-overlapping sets based on minimum value of Capacity-StrengthTotal for each group
    GroupId     Batches     StrengthStr     StrengthTotal     Capacity
    1.     {BIT-10, BIT-11, BICSE-7}     {35, 40, 25}     100     100
    2.     {BSCS-3, BESE-3}     {40, 30}     70     70
    3.     {BSCS-2, BEE-4}     {35, 50}     85     90
    And finally, the final result must have all the batches in it...
    Which in this case is true...
    Any help will be highly appreciated...
    Thanks
    Bilal

    Is this not a duplicate thread?
    Re: SQL Query for mapping a set of batches to a class rooms group

  • SQL Query for members of dynamic group - Need to include Name, Path and Type

    Hello,
    I built a custom dynamic group that has all my SQL databases in it using SCOM 2012 SP1.  The group works fine as I can see the Name(ie, Database name), Health State, Path (ie, hostname/instance) and Types (ie; SQL 2005).  Now I'm trying to
    build a custom report based off this same information using a SQL query.   I'm no DBA and could use some help.  So far this is what i have
    use
    select
    SourceObjectDisplayName as
    'Group Name',
    TargetObjectDisplayName,TargetObjectPath
    from RelationshipGenericView
    where isDeleted=0
    AND SourceObjectDisplayName
    like
    'SQL_Databases_All'
    ORDERBY TargetObjectDisplayName
    This gets me the Group Name (which i really don't care about), database name, and hostname/instance. What I am missing is the Health State and most importantly the Type (ie, SQL Server 2005 DB, SQL Server 2008DB).
    If someone could assist me here I would appreciate it. I believe I need to do some type of INNER JOIN but have no idea where the SQL type info lives or the proper structure to use. Thanks
    OperationsManager

    Here's the updated Query for OpsMan 2012 R2:
    To find all members of a given group (change the group name below):
    select SourceObjectDisplayName as 'Group Name', TargetObjectDisplayName as 'Group Members' 
    from RelationshipGenericView 
    where isDeleted=0 
    AND SourceObjectDisplayName = 'Agent Managed Computer
    Group' 
    ORDER BY TargetObjectDisplayName

  • Need help with SQL Query with Inline View + Group by

    Hello Gurus,
    I would really appreciate your time and effort regarding this query. I have the following data set.
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*20.00*-------------19
    1234567----------11223--------------7/5/2008-----------Adjustment for bad quality---------44345563------------------A-----------------10.00------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765--------------------I---------------------30.00-------------19
    Please Ignore '----', added it for clarity
    I am trying to write a query to aggregate paid_amount based on Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number and display description with Invoice_type 'I' when there are multiple records with the same Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number. When there are no multiple records I want to display the respective Description.
    The query should return the following data set
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*10.00*------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765-------------------I---------------------30.00--------------19
    The following is my query. I am kind of lost.
    select B.Description, A.sequence_id,A.check_date, A.check_number, A.invoice_number, A.amount, A.vendor_number
    from (
    select sequence_id,check_date, check_number, invoice_number, sum(paid_amount) amount, vendor_number
    from INVOICE
    group by sequence_id,check_date, check_number, invoice_number, vendor_number
    ) A, INVOICE B
    where A.sequence_id = B.sequence_id
    Thanks,
    Nick

    It looks like it is a duplicate thread - correct me if i'm wrong in this case ->
    Need help with SQL Query with Inline View + Group by
    Regards.
    Satyaki De.

  • Urgent= How to Group selected columns in sql query

    Hi,
    I need some urgent help on the following sql query. I 'm sure there is an easy way to do this but I'm stacked!Any help will be much appreciated!!
    I have a query to retrieve the following columns:
    I want the first 9 columns to be grouped together (not to be repeated) for any occurence of the last 3 columns (abs.ABSENCE_START_DATE,abs.ABSENCE_END_DATE, abs.DAYS_TAKEN DAYS_TAKEN_analysis)
    SELECT DISTINCT
    sum.employee_number ,
    sum.EMPLOYEE_NAME,
    sum.EMAIL_ADDRESS,
    sum.ORGANIZATION ,
    sum.BCEBF ,
    sum.ALDE ,
    sum.CURYRREMDAYS ,
    sum.DAYS_TAKEN ,
    sum.REMBCE ,
    abs.ABSENCE_START_DATE
    abs.ABSENCE_END_DATE,
    abs.DAYS_TAKEN DAYS_TAKEN_analysis
    --TO_CHAR(TO_CHAR(abs.ABSENCE_START_DATE)||' '||TO_CHAR(abs.ABSENCE_END_DATE)||' '||TO_CHAR(abs.DAYS_TAKEN)) DAYS_TAKEN_ANAL
    FROM
    HB_V_ANNUAL_LEAVE_SUMMARY_REP SUM,
    HB_V_AN_LEAV_DAYS_TAKEN_REP ABS
    WHERE
    sum.employee_number = abs.EMPLOYEE_NUMBER
    ORDER BY
    sum.employee_number ,
    sum.EMPLOYEE_NAME,
    sum.EMAIL_ADDRESS,
    sum.ORGANIZATION ,
    sum.BCEBF ,
    sum.ALDE ,
    sum.CURYRREMDAYS ,
    sum.DAYS_TAKEN ,
    sum.REMBCE
    Any feedback/help on how to do this will be highly appreciated.
    Thanks a lot
    Elena

    Please help!!
    I used the break command to group columns that I do not want to repeat in my query output. When I run the query without formatting is working. But when I put all formatting to produce the required output I dont get the result I want.
    Below is the exact sql query I use:
    <<
    SET TERMOUT OFF
    SET ECHO OFF
    SET ARRAY 35
    SET HEA OFF
    SET FEEDBACK OFF
    SET PAGES 2000
    col beginLINE format A100
    col winsecidLINE format A100
    col placeLINE format A100
    COL LINEempty1 format A100
    COL LINEempty2 format A100
    COL LINEempty3 format A100
    COL LINEempty4 format A100
    COL LINEempty5 format A100
    COL LINEempty6 format A100
    COL LINEempty7 format A100
    COL LINEempty8 format A100
    COL LINEempty9 format A100
    COL LINEempty10 format A100
    col LINECOLempty format A100
    col receiverLINE FORMAT A100
    COL EMP_EMAIL_ADDRESS FORMAT A100
    COL LINEHEADER FORMAT A100
    COL unitsLINE FORMAT A100
    COL lmLINE FORMAT A100
    COL INTITLE FORMAT A100
    COL LINECOL1 FORMAT A100
    COL CIF FORMAT A100
    COL EMPLOYEE_NAME FORMAT A100
    COL ORGANIZATION FORMAT A100
    COL LINECOL2 FORMAT A100
    COL ALHEADER FORMAT A100
    col LINECOL3 FORMAT A100
    col BCEBF FORMAT A100
    col ALDE FORMAT A100
    COL CURYRREMDAYS FORMAT A100
    COL DAYS_TAKEN FORMAT A100
    col LINECOL4 FORMAT A100
    COL REMBCE FORMAT A100
    col LINECOL5 FORMAT A100
    col LINECOL6 FORMAT A100
    col ALHEADER2 FORMAT A100
    col LINECOL7 FORMAT A100
    col endLINE FORMAT A100
    break on beginLINE on winsecidLINE on placeLINE on LINEempty1 ON LINEempty2 ON LINEempty3 ON LINEempty4 ON LINEempty5 ON LINEempty6 ON LINEempty7 ON LINEempty8 ON LINEempty9 ON LINEempty10 on receiverLINE on EMP_EMAIL_ADDRESS on LINEHEADER on unitsLINE on lmLINE on INTITLE on LINECOL1 on CIF on EMPLOYEE_NAME on ORGANIZATION on LINECOL2 on ALHEADER on LINECOL3 on BCEBF on ALDE on CURYRREMDAYS on DAYS_TAKEN on LINECOL4 on REMBCE on LINECOL5 on LINECOL6 on ALHEADER2 on LINECOL7 ON LINEempty11 ON endREPORT on endLINE
    SPOOL C:\FORMATout.txt
    SELECT
    '{{begin}} '||chr(10) beginLINE,
    '{{winsecid 999999}} '||chr(10) winsecidLINE,
    '{{place rbsemail.tif 0 0}} '||chr(10) placeLINE,
    ' '||chr(10) LINEempty1,
    ' '||chr(10) LINEempty2,
    ' '||chr(10) LINEempty3,
    ' '||chr(10) LINEempty4,
    ' '||chr(10) LINEempty5,
    ' '||chr(10) LINEempty6,
    ' '||chr(10) LINEempty7,
    ' '||chr(10) LINEempty8,
    ' '||chr(10) LINEempty9,
    ' '||chr(10) LINEempty10,
    '{{from [email protected]}} '||chr(10) receiverLINE,
    '{{fax '|| EMAIL_ADDRESS||' }} '||chr(10) EMP_EMAIL_ADDRESS,
    '{{Subject Annual Leave Summary Report as at '||sysdate||' }} '||chr(10) LINEHEADER,
    '{{units cm}} '||chr(10) unitsLINE,
    '{{lm 2.0}} '||chr(10) lmLINE,
    'ANNUAL LEAVE SUMMARY REPORT AS AT '||sysdate INTITLE,
    '---------------------------------------------------------------------' LINECOL1,
    'CIF: '||CIF CIF,
    'EMPLOYEE NAME: '||EMPLOYEE_NAME EMPLOYEE_NAME,
    'DEPARTMENT DETAILS: '||ORGANIZATION ORGANIZATION,
    '---------------------------------------------------------------------' LINECOL2,
    'ANNUAL LEAVE DETAILS:' ALHEADER,
    '---------------------------------------------------------------------' LINECOL3,
    'BALANCE B/F FROM PREVIOUS YEAR: '||BCEBF BCEBF,
    'DAYS ENTITLED FOR THE CURRENT YEAR: '||ALDE ALDE,
    'CURRENT YEAR REMAINING DAYS: '||CURYRREMDAYS CURYRREMDAYS,
    'DAYS TAKEN FOR THE CURRENT YEAR: '||DAYS_TAKEN DAYS_TAKEN,
    '---------------------------------------------------------------------' LINECOL4,
    'REMAINING BALANCE: '||REMBCE REMBCE,
    '---------------------------------------------------------------------' LINECOL5,
    '---------------------------------------------------------------------' LINECOL6,
    'ANNUAL LEAVE DAYS TAKEN ANALYSIS FOR THE CURRENT YEAR:' ALHEADER2,
    '---------------------------------------------------------------------' LINECOL7,
    TO_CHAR('START DATE: '||ABSENCE_START_DATE||' '||'END DATE: '||ABSENCE_END_DATE||' '||'DAYS TAKEN : '||DAYS_TAKEN_ANAL) AL_DAYS_ANAL,
    ' '||chr(10) LINEempty11,
    '-- End of Report -- '||chr(10) endREPORT,
    '{{end}} '||chr(10) endLINE
    FROM HB_V_AN_LEAV_SUM_DAYSTAKEN_REP
    WHERE CIF IN ('098033','098024')
    ORDER BY
    beginLINE ,
    winsecidLINE,
    placeLINE ,
    LINEempty1,
    LINEempty2,
    LINEempty3,
    LINEempty4,
    LINEempty5,
    LINEempty6,
    LINEempty7,
    LINEempty8,
    LINEempty9,
    LINEempty10,
    receiverLINE,
    EMP_EMAIL_ADDRESS,
    LINEHEADER ,
    unitsLINE ,
    lmLINE ,
    INTITLE ,
    LINECOL1,
    CIF ,
    EMPLOYEE_NAME ,
    ORGANIZATION ,
    LINECOL2 ,
    ALHEADER ,
    LINECOL3,
    BCEBF ,
    ALDE ,
    CURYRREMDAYS ,
    DAYS_TAKEN ,
    LINECOL4 ,
    REMBCE ,
    LINECOL5 ,
    LINECOL6 ,
    ALHEADER2 ,
    LINECOL7 ,
    LINEempty11,
    endREPORT,
    endLINE
    spool off
    >>
    The required output I want to get is:
    <<
    {{begin}}
    {{winsecid 750612}}
    {{place rbsemail.tif 0 0}}
    {{from [email protected]}}
    {{fax [email protected] }}
    {{Subject Annual Leave Summary Report as at 04-APR-08 }}
    {{units cm}}
    {{lm 2.0}}
    ANNUAL LEAVE SUMMARY REPORT AS AT 04-APR-08
    CIF: 098024
    EMPLOYEE NAME: Christou Christos Panteli
    DEPARTMENT DETAILS: 003-031-010-314-03140-Special Projects
    ANNUAL LEAVE DETAILS:
    BALANCE B/F FROM PREVIOUS YEAR: 9
    DAYS ENTITLED FOR THE CURRENT YEAR: 27
    CURRENT YEAR REMAINING DAYS: 24
    DAYS TAKEN FOR THE CURRENT YEAR: -3
    REMAINING BALANCE: 33
    ANNUAL LEAVE DAYS TAKEN ANALYSIS FOR THE CURRENT YEAR:
    START DATE: 04-JAN-08 END DATE: 04-JAN-08 DAYS TAKEN : 1
    START DATE: 24-JAN-08 END DATE: 24-JAN-08 DAYS TAKEN : 1
    START DATE: 20-FEB-08 END DATE: 20-FEB-08 DAYS TAKEN : 1
    -- End of Report --
    {{end}}
    {{begin}}
    {{winsecid 750612}}
    {{place rbsemail.tif 0 0}}
    {{from [email protected]}}
    {{fax [email protected]}}
    {{Subject Annual Leave Summary Report as at 04-APR-08 }}
    {{units cm}}
    {{lm 2.0}}
    ANNUAL LEAVE SUMMARY REPORT AS AT 04-APR-08
    CIF: 098033
    EMPLOYEE NAME: Demetriou Elena Steliou
    DEPARTMENT DETAILS: 003-031-010-314-03140-Special Projects
    ANNUAL LEAVE DETAILS:
    BALANCE B/F FROM PREVIOUS YEAR: 15
    DAYS ENTITLED FOR THE CURRENT YEAR: 27
    CURRENT YEAR REMAINING DAYS: 25
    DAYS TAKEN FOR THE CURRENT YEAR: -2
    REMAINING BALANCE: 40
    ANNUAL LEAVE DAYS TAKEN ANALYSIS FOR THE CURRENT YEAR:
    START DATE: 15-JAN-08 END DATE: 15-JAN-08 DAYS TAKEN : 1
    START DATE: 24-MAR-08 END DATE: 24-MAR-08 DAYS TAKEN : 1
    -- End of Report --
    {{end}}
    >>
    However the actual output we get from the above query is as follows:
    <<
    {{begin}}
    {{winsecid 750612}}
    {{place rbsemail.tif 0 0}}
    {{from [email protected]}}
    {{fax [email protected] }}
    {{Subject Annual Leave Summary Report as at 04-APR-08 }}
    {{units cm}}
    {{lm 2.0}}
    ANNUAL LEAVE SUMMARY REPORT AS AT 04-APR-08
    CIF: 098024
    EMPLOYEE NAME: Christou Christos Panteli
    DEPARTMENT DETAILS: 003-031-010-314-03140-Special Projects
    ANNUAL LEAVE DETAILS:
    BALANCE B/F FROM PREVIOUS YEAR: 9
    DAYS ENTITLED FOR THE CURRENT YEAR: 27
    CURRENT YEAR REMAINING DAYS: 24
    DAYS TAKEN FOR THE CURRENT YEAR: -3
    REMAINING BALANCE: 33
    ANNUAL LEAVE DAYS TAKEN ANALYSIS FOR THE CURRENT YEAR:
    START DATE: 04-JAN-08 END DATE: 04-JAN-08 DAYS TAKEN : 1
    -- End of Report --
    {{end}}
    START DATE: 24-JAN-08 END DATE: 24-JAN-08 DAYS TAKEN : 1
    START DATE: 20-FEB-08 END DATE: 20-FEB-08 DAYS TAKEN : 1
    {{fax [email protected] }}
    {{Subject Annual Leave Summary Report as at 04-APR-08 }}
    {{units cm}}
    {{lm 2.0}}
    ANNUAL LEAVE SUMMARY REPORT AS AT 04-APR-08
    CIF: 098033
    EMPLOYEE NAME: Demetriou Elena Steliou
    DEPARTMENT DETAILS: 003-031-010-314-03140-Special Projects
    ANNUAL LEAVE DETAILS:
    BALANCE B/F FROM PREVIOUS YEAR: 15
    DAYS ENTITLED FOR THE CURRENT YEAR: 27
    CURRENT YEAR REMAINING DAYS: 25
    DAYS TAKEN FOR THE CURRENT YEAR: -2
    REMAINING BALANCE: 40
    ANNUAL LEAVE DAYS TAKEN ANALYSIS FOR THE CURRENT YEAR:
    START DATE: 15-JAN-08 END DATE: 15-JAN-08 DAYS TAKEN : 1
    -- End of Report --
    {{end}}
    START DATE: 24-MAR-08 END DATE: 24-MAR-08 DAYS TAKEN : 1
    >>
    IF ANYONE CAN HELP ON THIS I WOULD REALLY APPRECIATE IT!
    THANKS A LOT!
    Best regards,
    Elena

  • SQL select group by Query

    Suppose a table T1 has 2 columns C1 and C2 and data as follows:
    C1 C2
    == ==
    1 A1
    1 A2
    2 B1
    2 B2
    2 B3
    3 C1
    4 D1
    4 D2
    I want to write a SQL query to select data and display as follows (i.e. grouped by C1, but C2 should display as single field with say '-' seperator):
    C1 C2-Details
    == ========
    1 A1-A2
    2 B1-B2-B3
    3 C1
    4 D1-D2
    Please help.
    Thanks in advance
    Goli

    Your query maybe like this
    SELECT c1,
    LTRIM(MAX(SYS_CONNECT_BY_PATH(c2,'-'))
    KEEP (DENSE_RANK LAST ORDER BY curr),'-') AS employees
    FROM (SELECT c1,
    c2,
    ROW_NUMBER() OVER (PARTITION BY c1 ORDER BY c2) AS curr,
    ROW_NUMBER() OVER (PARTITION BY c1 ORDER BY c2) -1 AS prev
    FROM t1)
    GROUP BY c1
    CONNECT BY prev = PRIOR curr AND c1 = PRIOR c1
    START WITH curr = 1;

Maybe you are looking for