Grouping consecutive rows with same value?

Hi
I have a table in which three columns are:
ROWID  SHOPNAME
1      SHOP_C     
2      SHOP_A     
3      SHOP_C     
4      SHOP_C     
5      SHOP_A     
6      SHOP_A     
7      SHOP_C     
8      SHOP_B     
9      SHOP_B     
10     SHOP_E    
11     SHOP_A     
12     SHOP_D     
13     SHOP_D     
14     SHOP_F     
15     SHOP_G     
16     SHOP_F     
17     SHOP_C     
18     SHOP_C     
19     SHOP_C     
20     SHOP_C      Rowid is a primary key column with unique ids
Shopname is varchar2 column
I want to make groupings of every "shopname" value "order by ROWID" such that when there are consecutive rows of same shopname the group remains same and as soon as there is different value in shopname column for the next row the "group" changes.
below is my desired output is with 3rd column of groupings as follows:
ROWID  SHOPNAME    Groups
1      SHOP_C      1
2      SHOP_A      2
3      SHOP_C      3 ------> same grouping because Shop name is same
4      SHOP_C      3 ------> same grouping because shop name is same
5      SHOP_A      4 ----> different shopname so group changed.
6      SHOP_A      4 ----> same group as above because shopname is same
7      SHOP_C      5
8      SHOP_B      6
9      SHOP_B      6
10     SHOP_E      7
11     SHOP_A      8
12     SHOP_D      9
13     SHOP_D      9
14     SHOP_F      10
15     SHOP_G      11
16     SHOP_F      12
17     SHOP_C      13
18     SHOP_C      13
19     SHOP_C      13
20     SHOP_C      13I want that to be done via analytics, so that I can partition by clause for different shops over different cities
regards
Ramis.

with data(row_id, shop) as
select 1,      'SHOP_C' from dual union all
select 2,      'SHOP_A' from dual union all     
select 3,      'SHOP_C' from dual union all
select 4,      'SHOP_C' from dual union all    
select 5,      'SHOP_A' from dual union all     
select 6,      'SHOP_A' from dual union all
select 7,      'SHOP_C' from dual union all
select 8,      'SHOP_B' from dual union all
select 9,      'SHOP_B' from dual union all
select 10,     'SHOP_E' from dual union all
select 11,     'SHOP_A' from dual union all
select 12,     'SHOP_D' from dual union all
select 13,     'SHOP_D' from dual union all
select 14,     'SHOP_F' from dual union all
select 15,     'SHOP_G' from dual union all
select 16,     'SHOP_F' from dual union all
select 17,     'SHOP_C' from dual union all
select 18,     'SHOP_C' from dual union all
select 19,     'SHOP_C' from dual union all
select 20,     'SHOP_C' from dual
get_data as
  select row_id, shop,
         lag(shop) over (order by row_id) prev_shop
    from data
select row_id, shop,
       sum(case when shop = prev_shop
                  then  0
                  else 1
                  end
            ) over (order by row_id) grps
  from get_data;
ROW_ID SHOP   GRPS
     1 SHOP_C    1
     2 SHOP_A    2
     3 SHOP_C    3
     4 SHOP_C    3
     5 SHOP_A    4
     6 SHOP_A    4
     7 SHOP_C    5
     8 SHOP_B    6
     9 SHOP_B    6
    10 SHOP_E    7
    11 SHOP_A    8
    12 SHOP_D    9
    13 SHOP_D    9
    14 SHOP_F   10
    15 SHOP_G   11
    16 SHOP_F   12
    17 SHOP_C   13
    18 SHOP_C   13
    19 SHOP_C   13
    20 SHOP_C   13
20 rows selected

Similar Messages

  • Group Record Number for consecutive Rows with same value.

    I have following Data in TEST table
    END_DATE      HOURS
    ====================
    8/30/2012     20
    7/30/2012     30
    7/1/2012 30     
    6/30/2012     20
    5/30/2012     20
    5/1/2012     20
    I would like to get the following result (GRP_REC_NUM column)
    END_DATE      HOURS GRP_REC_NUM
    ============================
    8/30/2012     20 1
    7/30/2012     30 1
    7/1/2012 30     2
    6/30/2012     20 1 *<<----- This should reset back to 1*
    5/30/2012     20 2
    5/1/2012     20 3
    Thanks
    slokam

    slokam wrote:
    I would like to get the following result (GRP_REC_NUM column)
    END_DATE      HOURS GRP_REC_NUM
    ============================
    8/30/2012     20 1
    7/30/2012     30 1
    7/1/2012 30     2
    6/30/2012     20 1 *<<----- This should reset back to 1*
    5/30/2012     20 2
    5/1/2012     20 3
    I could not understand why 5/30/2012 has the Rec_num column as 2. According to my understanding, you are trying to assign Ranks to each of the Dates. And if it is so, then 7/1/2012 should have GROUP_REC_NUM as 1 and 7/30/2012 as 2.
    Since, it is not clear about the logic to assign ranks, it will be helpful (for you as well as us) if you can elaborate the logic.
    Below is probably what you need.
    with data as
    select to_date('08/30/2012', 'MM/DD/YYYY') dt, 20 hrs from dual union all
    select to_date('07/30/2012', 'MM/DD/YYYY') dt, 30 hrs from dual union all
    select to_date('07/1/2012', 'MM/DD/YYYY') dt, 30 hrs from dual union all
    select to_date('06/30/2012', 'MM/DD/YYYY') dt, 20 hrs from dual union all
    select to_date('05/30/2012', 'MM/DD/YYYY') dt, 20 hrs from dual union all
    select to_date('05/1/2012', 'MM/DD/YYYY') dt, 20 hrs from dual
    select dt, hrs,
           dense_rank() over (partition by to_char(dt, 'MM') order by dt) rn
      from data
    order by dt;
    DT                        HRS                    RN                    
    01-MAY-12                 20                     1                     
    30-MAY-12                 20                     2                     
    30-JUN-12                 20                     1                     
    01-JUL-12                 30                     1                     
    30-JUL-12                 30                     2                     
    30-AUG-12                 20                     1

  • Counting one of multiple rows with same value for same ID

    Hello,
    I have this query:
    SELECT
    count( case when EXISTS (
                SELECT *
                FROM  business_log bl, subject su
                WHERE  su.ID_SUBJECT = s.ID_SUBJECT
                and bl.id_subject = su.id_subject
                AND    bl.value = 'Solved'
    then 1 else null end) num_solved
    FROM subject s
    It is posible that one subject is more than once 'Solved' in table BUSINESS_LOG
    I want to count only one row solved for one subject.
    I must to use only SUBJECT table in the main query because of other counts.
    Thank You very much.
    Regards
    Milos
    Message was edited by: 2796614

    so in case you have no solved entry...you get NULL back instead of 0.....
    and....there is no need for the group by ....as you are only looking for one subject
    SELECT COALESCE((SELECT max(1)
                      FROM  business_log bl
                     WHERE bl.id_subject = s.id_subject
                       AND bl.value = 'Solved'),0) num_solved
      FROM subject s
    but....I would like to have a proof, that this one is faster than the outer-join solution.
    So...perhaps we'll see an execution plan for both of them.
    corrected....missing bracket

  • Macro/VBA script to merge rows with same values in another column

    Hi.
    I'm developing a dance competition application, using Excel 2010, and have so far managed to put judges' marked scores into a worksheet through a userform.
    Now I would like to make the worksheet more presentable as a scoreboard, as you would manually, but via VBA scripts.
    Exhibit Numbers (Column G) are unique identifiers (per competition) for contestants and each contestant is typically judged by three judges.  The scores in three separate categories from one judge would spread in one row so each contestant would have three
    rows.
    I would like to merge rows of columns where the totals from the judges go (Columns P to U) for each contestant.
    I've considered using some kind of loop but I don't have enough experience in vba scripting, it gets overcomplicated. Could someone please help?
    Many thanks.
    Maki Koyama (Canberra, AUS)

    Hi,
    You cannot add a static "Y" inside a when looping over "i". You need to ensure that "Y" changes along with X. Try the modified code below.
    List elements = new ArrayList();
    for (int i=0; i<XXX; i++) {
    IZZZ.IVisibilityElement el = wdContext.createVisibilityElement();
    el.setVisAttr(i); // Change Y to i
    elements.add(el);
    wdContext.nodeVisibility().bind(elements);
    That should give you an idea of what is erroneous in the code.
    Thanks.
    HTH.
    p256960

  • How to merge rows with similar values in alv grid display in webdynpro

    Hi experts,
                   i want to know about how to merge rows with similar values in alv grid display of webdynpro.grouping rows is possible in table display in webdynpro but i am not able to do row grouping in the alv grid display in webdynpro.
    kindly suggest.
    thanks ,
    Anita.

    Hi Anita,
    did you find a solution for this? I have opened a Thread, if you know the answer maybe you could help me out:
    Is there an ALV function similar to the TABLE Row grouping?
    Thanx in advanced!!!
    Kind Regards,
    Gerardo J

  • Updating PK with same value - effect on CASCADE UPDATE

    Hello,
    I would like to understand how sql server 2008 deals with cascade updates
    For example I have
    Parent table: Employee with column Id as varchar(20) primary key
    Child table with IdEmployee as varchar(20) foreign key
    I set up Cascade Update for those two tables, meaning any change to primary key in Employee table will cause update in child table rows that match affecting Id
    Scenario 1:
    Update Employee
    set Id = 'ABC',
    Name = 'something new'
    where Id = 'CCC'
    Result of child table: all rows with foreign key IdEmployee and value of 'CCC' are updated. Expected behavior.
    Scenario 2:
    Update Employee
    set Id = 'ABC',
    Name = 'something new 2'
    where Id = 'ABC'
    This time, i am doing something different. I am beside update of column Name with new value, also update primary key but
    with SAME value
    Question is: what is going to happen to child rows? Are they ALL going to UPDATE due to CASCADE UPDATE
    So far, what i did in order to find solution is:
    1. I put an timestamp column in child table that should update each time row gets updated
    2. I put a trigger for update event on child table that will write something to some log table
    *After I set up those two I ran example like above just to be sure timestamp gets changed as well trigger is being fired
    Results of updating PK with same value:
    1. Timestamp didnt change
    2. Trigger didnt fire
    Is this enough to make conclusion that updating primary key with same value ALONG with updating some other columns won't
    affect child tables with UPDATE CASCADE ON
    Update:
    Database is CI AS collation
    If i do following
    Update Employee
    set Id = 'abc',
    Name = 'something new'
    where Id = 'ABC'
    1. Timestamp will change
    2. Trigger will fire
    Conclusion: Case sensitive is important here!
    Thank you very much in advance
    Milos

    >>  would like to understand how sql server 2008 deals with cascade updates <<
    Your posting has a number of conceptual errors. 
    1. The terms “parent” and “child” are not RDBMS; they are used in network databases. We have “referenced” and “referencing” tables; they can be the same table.
    2. A table models a SET of things, so there is no “Employee” table unless you truly have a one-man company. We want a collective or plural name for the SET/table. A better name is “Personnel” for this table. 
    3. Her is no such thing as a generic “id” in RDBMS; it has to be “<something in particular>_id” to be valid. Identifiers are usually fixed length 
    4. It is very, very rude not to post DDL on a forum. You also do not know the ISO-11179 Rules for data element names. They do not change names from table to table! Does your name change whenever you use it in a new place?? NO! Same principle with data. 
    5. The ISO standard uses “<property>_<attribute property>” syntax, no the old PascalCase.
    6. Why did you post a useless narrative? How do we compile “I SET up Cascade UPDATE for those two tables,..” to test it?? 
    CREATE TABLE Personnel
    (emp_id CHAR(20) NOT NULL PRIMARY KEY,
     emp_name VARCHAR(25) NOT NULL,
    CREATE TABLE Health_Plan
    (health_plan_acct CHAR(20) NOT NULL PRIMARY KEY,
     emp_id CHAR(20) NOT NULL 
     REFERENCES Personnel(emp_id)
     ON UPDATE CASCADE
     ON DELETE CASCADE,
    Scenario 1:
    UPDATE Personnel
       SET emp_id = 'ABC',
           emp_name = 'something new'
     WHERE emp_id = 'CCC';
    Result of child table: all rows with foreign key emp_id and value of 'CCC' are updated. Expected behavior.
    Scenario 2:
    UPDATE Personnel
       SET emp_id = 'ABC',
           emp_name = 'something new 2'
     WHERE emp_id = 'ABC';
    This time, I am doing something different. I am beside UPDATE of column emp_name with new value, also UPDATE PRIMARY KEY but
    with SAME value.
    >> Question is: what is going to happen to child [sic: referencing]  rows? Are they ALL going to UPDATE due to CASCADE UPDATE. <<
    SQL uses a set-oriented model, so the whole table is updated as a unit of work in theory. 
    So far, what I did in order to find solution is:
    >> I put an timestamp column in child [sic: referencing] table that should UPDATE each time row gets updated <<
    Why? It is not in the SET clause list; it cannot change. As an aside,  The T-SQL TIMESTAMP is not the ANSI/ISO TIMESTAMP; it is DATETIME2(n) in T-SQL. The old TIMESTAMP is being deprecated because it stinks both in concept and implementation. 
    >> I put a trigger for UPDATE event on child [sic: referencing] table that will write something to some log table.<<
    TRIGGERs are fired by what is called a “database event” shown in the ON [DELETE | UPDATE] clause. T-SQL adds INSERT as an event. An update to any value or to no value at all is still an update. Depending on the collation, case may or may not matter in the final
    outcome. 
    --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

  • Deleting  rows with missing values in field in start routine of update rule

    Hello experts,
    how can I delet rows with missing values in a specific field in the start routine of update rules?
    I think ABAP code should look something like this:
    delete ...  from DATA_PACKAGE where Z_NO = ''.
    thanks in advance for any suggestions!
    hiza

    Write:
    delete data_package where field = value.
    Hope it helps.
    Regards

  • Clearing WHT on advance & Invoice with same value

    Hi SAP Gurus
    Could anybody suggest me what transaction code to be used or need any configuration change for clearing both the doc i.e. WHT deduct on advance payment with WHT deducted on Invoice with same value.
    In this scenario no further payment should be made.
    I have linked both the doc through TCode F-54 and try to clear both the doc with TCode F-44 but in this transaction no tds has been reveresed by the system and showing difference.
    In Partial advance payment the system has automatically reversed the TDS. No problem occured in this scenario.
    Regards
    Aman
    Edited by: Amandeep Garg on Mar 17, 2008 10:43 AM

    Hi Ahmed
    Thanx for your response...............
    But I have already used the same. Is there not any transaction other than F-53 in which bank is not  invovled.
    Regards
    Aman

  • Show rows with empty values

    Hello,
    We are creating a cross tab report, with products as the columns, and relationship managers with direct and shared revenue displayed across the rows.
    For Eg
    Relationship Manager    Coverage         Product1   Product2   Product3   Product4
    Bob                                Direct                 100,           0,               35,            50
                                          Shared                0,              0,               15,            0
    Alex                               Direct                  15,            25,             40,            10
                                          Shared                5,              0,               5,               0
    George                          Direct                  0,               0,              0,               30
                                          Shared                0,               0,              0,               5
    The problem lies when either one of the products has no values, or one of the relationship managers has no direct or shared revenues. If one of the products has no revenues, it disappears, and also when one of the RMs has no direct or shared revenues, the Direct or Shared row disappears.
    I have tried to create a second query just included the Coverage variable, and using this variable in Query 2 with the RM variable from query 1, along with checking the "Show Rows with Empty Measure values", "Show Rows with Empty Dimension Values" and "Show when empty", but it still does not appear to work.
    It only shows rows with values in them, and shows the rows with empty values at the end with no RM.
    I have not tried to solve for empty columns yet.
    Help with this would be much appreciated!!!!!!!!
    Thank you

    Hi ,
    I think you can resolve this issue following ways ,
    you need create another query  ( Ex :Qauery2 ) add Product object and RM (Direct,shared) object only without  conation. So now query2 result wil have all product and RM(Direct,shared).
    Merge the Product object and RM  between query1 and query2
    Now create table using Product and RM from query2 and measure value from query1.  Now you will get row even there is no data.
    If you want try this sample report using efasion unvierse.
    1) Add year ,state and Discount objects  and apply condition Year Not in list "2004"  and state Not in list "California "
    2) run this query and create the cross tab table . Now you will not get 2004 column  and California row in table.
    3) Create query2 add Year and State only without any condition , run the query. Now query 2 will display all state and year .
    4) Merge the column Year and State between query1 and query2
    4) Create the cross table ussing Year and state from query2 and Discount from Query1
    Now cross table will show 2004 and California ,even there is not in query 1.
    I hope this will help you.
    Ponnarasu
    Edited by: ponnarasuk on Dec 7, 2011 12:48 PM

  • Seperate Document Row with same account  when post GL

    Hello everyone
    How I can seperate Document Row with same account  when post GL
    because If I post dcoument that  have many rows but same account and difference detail. It will sum amount for same account in JE
    and I found that will seperate if it has diference project code but it's not enough for me.
    How I can config SAP B1 to seperate Doc row when post to JE if it has difference detail (as userfield or standard filed)
    Sorry for my poor english
    Thank,Seang

    Hello Suthee,
    Sorry to tell you, it is not possible to do so in current B1 without addon development.
    There are 2 alternative.
    1.Consulting Workaround:
    Seperate the Item into 2 items, the account into 2 sub accounts.e.g.
    Item A => Item A01 and A02
    G/L Account 1001 => Sub Account 100101 and 100102
    2.AddOn development to seperate the JE just after it is created document
    You can update to JE to seperate just after JE are created by docuemnts.
    Just Listen FormDataAdd Event.
    Sample Code:
    Private Sub FormDataEventHandler( _
        ByRef BusinessObjectInfo As SAPbouiCOM.BusinessObjectInfo, _
        ByRef BubbleEvent As Boolean) Handles oApp.FormDataEvent
            'I just listen 133 - AR invoice here,
            'You may add the target documents
            'Before action = true, start the transation
            If BusinessObjectInfo.FormTypeEx = "133" _
                    And (BusinessObjectInfo.EventType = SAPbouiCOM.BoEventTypes.et_FORM_DATA_ADD _
                    Or BusinessObjectInfo.EventType = SAPbouiCOM.BoEventTypes.et_FORM_DATA_UPDATE) _
                    And BusinessObjectInfo.BeforeAction = True Then
                oCompany.StartTransaction()
            End If
            'Before Action = false,
            'Update the JE in document
            'Succeed, commit, otherwise rollback
            If BusinessObjectInfo.FormTypeEx = "133" _
            And (BusinessObjectInfo.EventType = SAPbouiCOM.BoEventTypes.et_FORM_DATA_ADD _
            Or BusinessObjectInfo.EventType = SAPbouiCOM.BoEventTypes.et_FORM_DATA_UPDATE) Then
                If BusinessObjectInfo.BeforeAction = False And BusinessObjectInfo.ActionSuccess Then
                    Dim xmlDoc As System.Xml.XmlDocument = New System.Xml.XmlDocument
                    xmlDoc.LoadXml(BusinessObjectInfo.ObjectKey)
                    Dim objectKey As String
                    objectKey = xmlDoc.SelectSingleNode("//DocEntry").InnerText
                    Dim oDocument As SAPbobsCOM.Documents = Nothing
                    oDocument = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseOrders)
                    If oDocument.GetByKey(CInt(objectKey)) Then
                        Dim oJE As SAPbobsCOM.JournalEntries
                        oJE = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oJournalEntries)
                        If oJE.GetByKey(oDocument.TransNum) Then
                            '*Add you code to Update oJE lines here*
                            lRetCode = oJE.Update
                            If 0 <> lRetCode Then
                                oApp.MessageBox("Failed to update JE")
                                'roll back the whole transaction, including the document
                                oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)
                                Exit Sub
                            Else
                                'Commit the transaction
                                oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit)
                            End If
                        End If
                    End If
                End If
            End If
        End Sub
    Hope it helps. Thanks.
    Kind Regards
    -Yatsea

  • Updating multiple rows with different values

    Hi!
    I have a problem. I need to update more then 1000 rows with different values. How can I do it?
    For exsample i have table:
    id; color, date,
    1 red
    2 green
    3 white
    I need to update date field.
    Update table
    set date='01.02.03'
    where id=1
    Update table
    set date='01.03.03'
    where id=2
    Maybe there is way how to update multiple rows at one query?
    Sorry for my bad english.
    Thanks!

    Hi,
    You can try this
    UPDATE TABLE SET DATE = CASE
                        WHEN ID = 1 THEN TO_DATE('01-02-03','DD-MM-RR')
                        WHEN ID = 2 THEN TO_DATE('01-03-03','DD-MM-RR')
                        ENDcheers
    VT

  • Returning 250 rows with 1000 Values in "IN" Clause Oracle 10g On IBM AIX !!

    Hi,
    Recently we have done the OS migration of Oracle 10g Server from Windows Server to IBM AIX. Everything is fine, But today we came across one crucial bug in the code, i.e In the Select Query, though we're expecting 1000 rows with 1000 values in "IN" Clause , It's returning Only 250 rows. Where as it's returning 1000 rows in Windows Environment with 1000 values in "IN" Clause. I have browsed throgh Google for the resolution but failed to get that.
    This is something like,
    In Oracle 10g On windows :-
    select * from emp
    where dept_id in (1,2,3,...................1000);
    Assuming there  are the dept_id values in Emp table from 1 ... 1000, It's returning 1000 rows.
    In Oracle 10g On IBM AIX ,
    select * from emp
    where dept_id in (1,2,3,...................1000);
    Assuming there  are the dept_id values in Emp table from 1 ... 1000, It's returning 250 rows. Pls help me, what could be the reason for this. and what needs to be checked to fix this.
    Pls suggest !!!
    Raja

    mmmh. Did you compared the select count(*) from your_table; in the two cases.
    If the result is not good and nobody has deleted rows between migration and your test, you migration need to be replayed.
    Which migration did you select, Transportable database or exp/imp...?
    Edited by: Dba Z on 16 août 2009 08:56

  • Query to insert a row in a table with same values except 1 field.

    Suppose I have a table with 100 columns(fields).
    I want to insert a row with 99 fileds being the same as previous ones except one fileld being different.
    The table doesn't have any constraints.
    Kindly suggest a query to solve the above purpose..

    And for much more lazy people, a desc of table is shorter to write. :-)
    Then copy & paste into any editor, then mode column to add a comma after every column name in one shot.Or have the system do it for you. Be lazy.
    SELECT Column_Name || ',' FROM User_Tab_Columns where Table_Name = '';
    Indeed, it can be converted to a script called desc(.sql)
    SELECT Column_Name || ',' FROM User_Tab_Columns where Table_Name = '&1' ORDER BY Column_Id;
    Then desc or @desc.

  • How  to identfy  rows  with  same  column value

    Hi
    I have a table student
    id ( pkey)
    name
    class
    marks
    i need to check the existence of duplicate values like
    say the values are :
    id name class marks
    1 alan 6 85
    2 victor 4 97
    3 alan 6 85
    i need to know if there is any matching row in the table --- like in this case id=1 and id=3 have same value for all the columns except for id .
    so the result shud tell me the ids which have duplicate values for name , class , marks and also those ids for which there is no duplicacy
    for id= 1 i see that id= 3 has same values
    and id=2 has no duplicates
    how do i show it ??
    The result i expect is
    name class marks count
    alan 6 85 2
    victor 4 97 1
    Message was edited by:
    SHUBH

    EMP
    id name class marks
    1 alan 6 85
    2 victor 4 97
    3 alan 6 85
    You can use a self join to pull out the data which are almost duplicate without a column values here in this example without id the first and third records are duplicate.
    select e.id,e.name,e.class,e.marks from EMP e,EMP d where e.name=d.ename and e.class=d.class and e.marks=d.marks and e.id<>d.id;

  • Identifying and grouping consecutive rows in sql

    I have following data set:
    CREATE TABLE APPS.T1
      ROW_NUM               NUMBER,
      EFFECTIVE_START_DATE  DATE                    NOT NULL,
      EFFECTIVE_END_DATE    DATE                    NOT NULL,
      STATUS                VARCHAR2(30 BYTE)
    SET DEFINE OFF;
    Insert into APPS.T1
       (ROW_NUM, EFFECTIVE_START_DATE, EFFECTIVE_END_DATE, STATUS)
    Values
       (1, TO_DATE('07/01/2009 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('09/06/2009 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'VAC');
    Insert into APPS.T1
       (ROW_NUM, EFFECTIVE_START_DATE, EFFECTIVE_END_DATE, STATUS)
    Values
       (2, TO_DATE('03/20/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('03/31/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'VAC');
    Insert into APPS.T1
       (ROW_NUM, EFFECTIVE_START_DATE, EFFECTIVE_END_DATE, STATUS)
    Values
       (3, TO_DATE('08/06/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('08/22/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'VAC');
    Insert into APPS.T1
       (ROW_NUM, EFFECTIVE_START_DATE, EFFECTIVE_END_DATE, STATUS)
    Values
       (4, TO_DATE('08/23/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('08/26/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'VAC');
    Insert into APPS.T1
       (ROW_NUM, EFFECTIVE_START_DATE, EFFECTIVE_END_DATE, STATUS)
    Values
       (5, TO_DATE('08/27/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('08/27/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'VAC');
    COMMIT;
    SELECT * FROM APPS.T1
       ROW_NUM EFFECTIVE EFFECTIVE STATUS                       
             1 01-JUL-09 06-SEP-09 VAC                          
             2 20-MAR-11 31-MAR-11 VAC                          
             3 06-AUG-11 22-AUG-11 VAC                          
             4 23-AUG-11 26-AUG-11 VAC                          
             5 27-AUG-11 27-AUG-11 VAC                          
    5 rows selected.My requirement was that row number 3, 4 and 5 be grouped and treated as a single vacation record such that
    effective_start_date = 06-AUG-2011 and
    effective_end_date = 27-AUG-2011
    For this I wrote a query:
    SELECT effective_start_date,
           effective_end_date,
           CASE
              WHEN LAG (effective_end_date, 1) OVER (ORDER BY row_num) + 1 = effective_start_date
                 THEN 0
              WHEN LEAD (effective_start_date, 1) OVER (ORDER BY row_num) - 1 = effective_end_date
                 THEN 0
              ELSE 1
           END row_num
      FROM (SELECT * FROM T1)Now the data returned looks like:
    EFFECTIVE EFFECTIVE    ROW_NUM
    01-JUL-09 06-SEP-09          1
    20-MAR-11 31-MAR-11          1
    06-AUG-11 22-AUG-11          0
    23-AUG-11 26-AUG-11          0
    27-AUG-11 27-AUG-11          0
    5 rows selected.Now I can easily use MIN(effective_start_date) and MAX(effective_start_date) group by ROW_NUM to achieve the desired results
    SELECT   MIN (effective_start_date) start_dt,
             MAX (effective_start_date) end_dt,
             row_num
        FROM (SELECT effective_start_date,
                     effective_end_date,
                     CASE
                        WHEN LAG (effective_end_date, 1) OVER (ORDER BY row_num) + 1 = effective_start_date
                           THEN 0
                        WHEN LEAD (effective_start_date, 1) OVER (ORDER BY row_num) - 1 = effective_end_date
                           THEN 0
                        ELSE 1
                     END row_num
                FROM (SELECT *
                        FROM t1))
    GROUP BY row_num
      HAVING row_num = 0
    UNION
    SELECT effective_start_date start_dt,
           effective_start_date end_dt,
           row_num
      FROM (SELECT effective_start_date,
                   effective_end_date,
                   CASE
                      WHEN LAG (effective_end_date, 1) OVER (ORDER BY row_num) + 1 = effective_start_date
                         THEN 0
                      WHEN LEAD (effective_start_date, 1) OVER (ORDER BY row_num) - 1 = effective_end_date
                         THEN 0
                      ELSE 1
                   END row_num
              FROM (SELECT *
                      FROM t1))
    WHERE row_num = 1
    START_DT  END_DT       ROW_NUM
    01-JUL-09 01-JUL-09          1
    20-MAR-11 20-MAR-11          1
    06-AUG-11 27-AUG-11          0
    3 rows selected.All done BUT the problem is that there may be several groups of consecutive rows like this. In that case each group should be identified distinctly for GROUP BY clause to work as expected.
    I want to assign a unique number to each occurence of such group.
    How can I achieve this? Any ideas?
    Regards,
    Faraz
    Edited by: faanwar on May 10, 2012 3:36 PM

    Well, actually, you'll need to tweak it a bit. something such as in :Scott@my11g SQL>l
      1  with t (id, dstart, dend, status)
      2  as (
      3       select 1,to_date('01-JUL-09','dd-MON-YY'),to_date('06-SEP-09','dd-MON-YY'),'VAC' from dual
      4       union all select 2,to_date('20-MAR-11','dd-MON-YY'),to_date('31-MAR-11','dd-MON-YY'),'VAC' from dual
      5       union all select 3,to_date('06-AUG-11','dd-MON-YY'),to_date('22-AUG-11','dd-MON-YY'),'VAC' from dual
      6       union all select 4,to_date('23-AUG-11','dd-MON-YY'),to_date('26-AUG-11','dd-MON-YY'),'VAC' from dual
      7       union all select 5,to_date('27-AUG-11','dd-MON-YY'),to_date('27-AUG-11','dd-MON-YY'),'VAC' from dual
      8  )
      9  ------ end of sample data ------
    10  select min(dstart) dstart, max(dend) dend, status, count(*) aggrows
    11  from (
    12       select
    13       id
    14            ,dstart
    15            ,dend
    16            ,status
    17            ,dend
    18                 -sum(dend-dstart) over (partition by status order by dstart)
    19                 -row_number() over (partition by status order by dstart) grp
    20       from t
    21  )
    22  group by grp, status
    23* order by grp, status
    Scott@my11g SQL>/
    DSTART              DEND                STA    AGGROWS
    01/07/2009 00:00:00 06/09/2009 00:00:00 VAC          1
    20/03/2011 00:00:00 31/03/2011 00:00:00 VAC          1
    06/08/2011 00:00:00 27/08/2011 00:00:00 VAC          3

Maybe you are looking for