Select latest two records per group

hi there,
i've been googling around and still can't really find an appropriate solution to retrieve two most recent records per group in one sql. Is this even possible?
Let's say there is a MyLife table :
ID, Event , RecordedDate
1. 1, 'Fell down the stairs', '20-DEC-07'
2. 1, 'Fell down the stairs', '22-DEC-07'
3. 1, 'Fell down the stairs', '23-DEC-07'
4. 2, 'Tried to kiss santa', '23-DEC-07'
5. 3, 'Reindeer stolen', '24-DEC-07'
6. 4, 'Chimney Broke', '25-DEC-07'
Output should be :
2. 1, 'Fell down the stairs', '22-DEC-07'
3. 1, 'Fell down the stairs', '23-DEC-07'
4. 2, 'Tried to kiss santa', '23-DEC-07'
5. 3, 'Reindeer stolen', '24-DEC-07'
6. 4, 'Chimney Broke', '25-DEC-07'

I believe that something along these lines would be portable to most other databases.
SQL> SELECT id, event, recordeddate
  2  FROM mylife o
  3  WHERE recordeddate = (SELECT MAX(recordeddate) FROM mylife i
  4                        WHERE o.id = i.id)
  5  UNION ALL
  6  SELECT id, event, recordeddate
  7  FROM mylife o
  8  WHERE recordeddate = (SELECT MAX(recordeddate) FROM mylife i
  9                        WHERE o.id = i.id and
10                              i.recordeddate < (SELECT MAX(recordeddate)
11                                                FROM mylife ii
12                                                WHERE i.id = ii.id))
13  ORDER BY id, recordeddate;
        ID EVENT                     RECORDEDDAT
         1 Fell down the stairs      22-DEC-2007
         1 Fell down the stairs      23-DEC-2007
         2 Tried to kiss santa       23-DEC-2007
         3 Reindeer stolen           24-DEC-2007
         4 Chimney Broke             25-DEC-2007John

Similar Messages

  • How to use grouping by field and have a tatol of records per group

    Dear All
    I have a repiort that i have created but i want code that allows me to group the report by a certain field then i give a tatol number of records per each group.
    Thank you in advance
    William

    Hi William,
    Lets suppose itab be the final internal table u are displaying.
    First sort this by the group field.
    Now,
    declare a variable g_grp.
    data : g_grp(10) type c.
    loop at itab.
    at new group.
    g_grp = itab-group + g_grp.
    endat.
    at end of grp.
    write g_grp.
    clear : g_grp.
    endat.
    endloop.
    Regards,
    Sai

  • Sql maximum record per group question

    CREATE
    TABLE DBO.TEST
    ID INT
    , RECTYPE
    INT,SEQ
    INT, MAX0
    INT,MAX1
    INT,MAX2
    INT)
    INSERT
    INTO dbo.TEST
    SELECT
    1,1,1,3,2,3
    UNION
    ALL
    SELECT
    1,2,2,3,2,3
    UNION
    ALL
    SELECT
    1,2,3,3,2,3
    UNION
    ALL
    SELECT
    1,1,2,3,2,3
    --SELECT * FROM dbo.TEST
    how
    to find
    MAX seq
    for each ID
    and Rectype
    My result should be
    MAX0
    is maximum
    of seq
    group
    by ID
    MAX1
    is maximum
    of seq
    group
    by ID
    where rectype
    =1
    MAX2 id maximum
    of seq
    group
    by ID
    where rectype
    = 2
    ID Rectype   SEQ  MAX0     MAX1      MAX2
    1 1      1     3      2        3
    1 2      2     3      2        3
    1 2      3     3      2        3
    1 1      2     3      2        3

    This is a typical in-group computation, which can be performed through the following steps:
    1. Group the data by ID; each group has all data of an ID.
    2. Perform in-group computation: compute the maximum value of SEQ in this group and assign the result to MAX0.
    3. In-group computation: select in this group the records whose Rectype equals 1, compute the maximum value of SEQ and assign it to MAX1.
    4. In-group computation: select in this group the records whose Rectype equals 2, compute the maximum value of SEQ and assign it to MAX2. 
    The train of thought is clear, but it is difficult to write code for in-group computations in SQL. You have to transform the computation to the form that multi-layer relations are nested into N window functions.
    But the code will be complicated and difficult. I’m afraid you still won’t be able to figure it out the next time you run into the similar problem. I suggest you using esProc to help with the computation if there is not so much data. Because esProc supports
    in-group computation very well, you can solve the problem in it easily. The code in esProc is as follows: 
    IDs=test.group(ID)   //corresponds to step 1
           IDs.run(~.run(MAX0=IDs.~.max(SEQ)))          //step 2
           IDs.run(~.run(MAX1= IDs.~.select(Rectype==1).max(SEQ)))     //step 3
           IDs. run(~.run(MAX2= IDs.~.select(Rectype==2).max(SEQ)))    //step 4
    In the code, “~” represents each group. It is similar to a loop variable. And, steps 2, 3 and 4 can be integrated into one step:
           =IDs.run(~.run(MAX0=IDs.~.max(SEQ)), ~.run(MAX1= IDs.~.select(Rectype==1).max(SEQ)), ~.run(MAX2= IDs.~.select(Rectype==2).max(SEQ)) )          
    The computed result in the above is in the form of ResultSet, which is easy to integrate with Java or the reporting tool. 

  • Varchar to Datetime conversion and selecting latest datead records

    Hi:
    I've a table as below:
    ActionDate|Status|Name
    23/10/2012|Block|James
    24/10/2012|Open|James
    25/10/2012|Block|James
    20/09/2012|Block|Tanya
    17/09/2012|Block|Fox
    18/09/2012|Open|Fox
    27/08/2012|Block|Martin
    27/08/2012|Open|Martin
    Desired Output is as follows:
    ActionDate|Status|Name
    25/10/2012|Block|James
    20/09/2012|Block|Tanya
    Select those records only which has Block staus on most recent date. It will also eliminate those which has Open status on the same date.
    One more problem is the ActionDate field is actually Varchar2 type and there are mismatch as well. For example: some of those are in MM/DD/YYYY and
    some are in DD/MM/YYYY
    So, how can I convert these strings into formated date and make the desired output in a single query. Please let me know.
    Thanks/Tanvir

    Hi, Tanvir,
    853856 wrote:
    Hi:
    I've a table as below:
    ActionDate|Status|Name
    23/10/2012|Block|James
    24/10/2012|Open|James
    25/10/2012|Block|James
    20/09/2012|Block|Tanya
    17/09/2012|Block|Fox
    18/09/2012|Open|Fox
    27/08/2012|Block|Martin
    27/08/2012|Open|MartinWhenever you have a problem, please post CREATE TABLE and INSERT statements for your sample data.
    Desired Output is as follows:
    ActionDate|Status|Name
    25/10/2012|Block|James
    20/09/2012|Block|TanyaSee the forum FAQ {message:id=9360002} for how to format the ouptut on this site (among other things).
    Select those records only which has Block staus on most recent date. It will also eliminate those which has Open status on the same date.
    One more problem is the ActionDate field is actually Varchar2 type That's not a very good idea. This problem shows just one of the many reasons why you should always use DATE columns for date information.
    and there are mismatch as well. For example: some of those are in MM/DD/YYYY and
    some are in DD/MM/YYYYThe you have no way of knowing if '01/12/2012' means January 12 or December 1. The query below arbitrarily assumes that will be December 1.
    So, how can I convert these strings into formated date and make the desired output in a single query. Please let me know.
    Thanks/TanvirHere's one way:
    WITH     got_real_actiondate     AS
         SELECT     TO_DATE ( actiondate
                   , CASE
                             WHEN  SUBSTR (actiondate, 4, 2)     <= '12'
                         THEN  'MM/DD/YYYY'
                         ELSE  'DD/MM/YYYY'
                     END
                   )     AS real_actiondate
         ,     status
         ,     name
         FROM     a_table
    ,     got_r_num     AS
         SELECT     real_actiondate
         ,     status
         ,     name
         ,     ROW_NUMBER () OVER ( PARTITION BY  name
                                   ORDER BY          real_actindate     DESC
                             ,                CASE
                                              WHEN  status = 'Open'
                                         THEN  1
                                         ELSE  2
                                          END
                           ) AS r_num
         FROM    got_real_actiondate
    SELECT     real_actiondate
    ,     status
    ,     name
    FROM     got_r_num
    WHERE     r_num     = 1
    AND     status     != 'Open'
    ;This assumes that actiondate is in either 'DD/MM/YYYY' or 'MM/DD/YYYY' format, which is very optimistic. If you sometimes have other formats as well, and/or text that can't be interpreted as a date in any format, then see {message:id=4252963}
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    In the case of a DML operation (such as INSERT) the sample data should show what the tables are like before the DML, and the results will be the contents of the changed table(s) after the DML.
    Explain, using specific examples, how you get those results from that data.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}

  • Read-only report for two records

    I have a table that has two records per one parent record.
    I want to display these two records on a page containing read-only fields (items) of the parent record.
    I was thinking of just having two regions each of which would perform a SELECT to pull it's respective record.
    Would I have to create fields for each record to load the fields into and then make each field be read-only?
    I did this to load one of the records into a form:
    select field1, field2 into px_field1, px_field2 where...
    I just wondered if there was an easier way other than creating two sets of fields to hold each record.
    I tried some of the canned reports using the wizard. Easy enough to pull the two records but the formatting goes a mile to the right and this page is to be used for printing.
    Thanks,

    semaphore,
    Have you considered using a Master Detail form. The forms have record navigation and the detail columns of the form can be altered to Display As Standard Report Column making them read only. As well, the Master part of the form can also be configured to be read or display only.
    Jeff

  • Query to find the latest two transactions for each Group

    Hi All,
    Consider the following sets of records in a table test.
    Group---Tran_Dt---SlNo
    c1 10/10/2003 1
    c1 10/10/2003 2
    c1 10/10/2003 3
    c1 11/10/2003 1
    c2 10/10/2003 1
    c2 10/10/2003 2
    c2 11/10/2003 1
    c2 11/10/2003 2
    c2 11/10/2003 3
    c3 10/10/2003 1
    c3 10/10/2003 2
    c3 10/10/2003 3
    I want to list out the latest two transactions for each group irrespective of the slno and trans_dt as below:
    group tran_dt SlNo
    c1 11/10/2003 1
    c1 10/10/2003 3
    c2 11/10/2003 3
    c2 11/10/2003 2
    c3 10/10/2003 3
    c3 10/10/2003 2
    Any help on this would be appreciated.
    Thanks
    Walter Nicholas T

    Hi Walter,
    Please try following query.
    select Group,tran_dt,sino from
    select Group,tran_dt,sino,(DENSE_RANK()OVER (PARTITION BY Group ORDER BY tran_dt desc,sino desc)) rank from test
    ) where rank between 1 and 2
    Thanks,
    Samir

  • Select one record per person from multiple conditions

    Perhaps been staring at this too long and making changes to try and gather the correct population, but can't seem to figure it out at the moment. Trying to determine logic to select one record per person. If person has more than one record would like to choose the record that matches the sequence priority which is:
    AND CASE WHEN ac.primary_program_ind = 'N'                                       --Existing Students who have a new program (Continuing Law and added Business)
                                   AND ac.academic_period_admitted = ac.academic_period
                                   AND ac.student_population <> 'V'
                                   AND ac.program is not null THEN 'Y'
                                WHEN ac.primary_program_ind = 'Y'                                        --Visitors (Each term considered new)
                                   AND ac.student_population = 'V'
                                   AND ac.academic_period_admitted is not null THEN 'Y'
                                WHEN ac.primary_program_ind = 'Y'                                        --Normal Cases
                                   AND ac.academic_period_admitted is not null THEN 'Y' --= ac.academic_period THEN 'Y'
                       END = 'Y' Meaning that if the person has records that meet more than one of the above cases, it should choose the record matching the First Case of the case statement. If the records do not meet the first case at all then look to see if it meets the second case and if it does choose that record, etc.
    Sample Data:
    SELECT 363 AS PERSON_UID, '1875' AS ID, '201140' AS ACADEMIC_PERIOD, '201040' AS ACADEMIC_PERIOD_ADMITTED, 'UG' AS STUDENT_LEVEL, '' AS EXIST_NEWPROG, 'Y' AS VISITORS, 'Y' AS NORMAL, 'V' AS STUDENT_POPULATION, 'Y' AS PRIMARY_PROGRAM_IND, 'LA' AS PROGRAM FROM DUAL
    UNION SELECT 852, '1962', '201130', '201040', 'GR', '', '', 'Y', 'C', 'Y', 'MS'  FROM DUAL
    UNION SELECT 852, '1962', '201140', '201140', 'GR', 'Y', '', '', 'G', 'N', 'MBA' FROM DUAL
    UNION SELECT 852, '1962', '201140', '201040', 'GR', '', '', 'Y', 'G', 'Y', 'MS' FROM DUAL
    UNION SELECT 659, '1093', '201140', '200840', 'UG', '', '', 'Y', 'T', 'Y', 'BB' FROM DUALSo for the above data on ID '1962', I would like to select the record that has EXIST_NEWPROG = 'Y' and ignore the other rows for that ID. Note:EXIST_NEWPROG, VISITORS, NORMAL I added to sample data, these cols don't actually exist. Put in for easier display purpose to show what case statements are doing. The actual sql statement has many joins and where statements, but hopefully this simplification of the sql will be sufficient to derive a solution.
    WITH MULTIROWS AS
    SELECT 363 AS PERSON_UID, '1875' AS ID, '201140' AS ACADEMIC_PERIOD, '201040' AS ACADEMIC_PERIOD_ADMITTED, 'UG' AS STUDENT_LEVEL, '' AS EXIST_NEWPROG, 'Y' AS VISITORS, 'Y' AS NORMAL, 'V' AS STUDENT_POPULATION, 'Y' AS PRIMARY_PROGRAM_IND, 'LA' AS PROGRAM FROM DUAL
    UNION SELECT 852, '1962', '201130', '201040', 'GR', '', '', 'Y', 'C', 'Y', 'MS'  FROM DUAL
    UNION SELECT 852, '1962', '201140', '201140', 'GR', 'Y', '', '', 'G', 'N', 'MBA' FROM DUAL
    UNION SELECT 852, '1962', '201140', '201040', 'GR', '', '', 'Y', 'G', 'Y', 'MS' FROM DUAL
    UNION SELECT 659, '1093', '201140', '200840', 'UG', '', '', 'Y', 'T', 'Y', 'BB' FROM DUAL
    select *
    from multirows ac
    where  CASE WHEN ac.primary_program_ind = 'N'                                       --Existing Students who have a new program (Continuing Law and added Business)
                                   AND ac.academic_period_admitted = ac.academic_period
                                   AND ac.student_population <> 'V'
                                   AND ac.program is not null THEN 'Y'
                                WHEN ac.primary_program_ind = 'Y'                                        --Visitors (Each term considered new)
                                   AND ac.student_population = 'V'
                                   AND ac.academic_period_admitted is not null THEN 'Y'
                                WHEN ac.primary_program_ind = 'Y'                                        --Normal Cases
                                   AND ac.academic_period_admitted is not null THEN 'Y' --= ac.academic_period THEN 'Y'
                       END = 'Y'

    Hi,
    user1069723 wrote:
    Thanks Frank. I've been incorporating your solution and going over the data, (which is why it has taken so long to respond) and am getting closer, however the approach you provided excludes people who have a "RNum" of 2 or 3, but do not have a 1 at all. So people that only have a 2 and 3 OR only have a 2 or only have a 3 would not be captured, but if there is only one record, they would be missed.
    Here is another set of records of one person.
    SELECT 921 AS PERSON_UID, '8284' AS ID, '201130' AS ACADEMIC_PERIOD, '201030' AS ACADEMIC_PERIOD_ADMITTED, 'UG' AS STUDENT_LEVEL, '' AS EXIST_NEWPROG, 'Y' AS VISITORS, 'Y' AS NORMAL, 'V' AS STUDENT_POPULATION, 'Y' AS PRIMARY_PROGRAM_IND, 'LA' AS PROGRAM FROM DUAL
    UNION SELECT 921, '8284', '201140', '201040', 'UG', '', '', 'Y', 'F', 'Y', 'BB'  FROM DUAL
    Sorry, I can't reproduce the problem.
    If I add the two new rows of sample data that you posted today to the data you posted yesterday, then the query I posted yesterday produces:
    PERSON_UID ID   ACADEM ACADEM ST E V N S P PRO      R_NUM
           659 1093 201140 200840 UG     Y T Y BB           1
           363 1875 201140 201040 UG   Y Y V Y LA           1
           852 1962 201140 201140 GR Y     G N MBA          1
           921 8284 201130 201030 UG   Y Y V Y LA           1Io you get the correct output for the original ids?
    If I DELETE all the rows where id != 8284 I still get the same results for id=8284.
    'm using Oracle 11.1.0.6.0. What version are you running?
    Post your exact code, even iof you think you copied it from thsi site without any changes. Perhaps there was some subtle eidting mistake.
    I would like to select the record for Academic_Period = 201140 for this person. Is the problem that you're getting the wrong row for id=8284, or that you're not getting any output for id=8284?
    Why would you want to get the row with academic_period=201140? (Let's call this row A.) Why don't you want the other row for that person, the one with academic_period=201130? (Let's call this row B.) On both of those rows, primary_program_ind='Y' and academic_period_admitted is not NULL. The only significant difference between those two rows is that student_population='F' on row A, and it's 'V' on row B. Doesn't that mean that row B causes the CASE expression to return 3 ("Normal Case"), while row B makes it return 2 ("Visitor")? Doesn't that mean row B should be preferred to row A?
    Then again, perhaps this is just what you mean by saying that "term" is the main factor in deciding which row to select, and that the CASE expreesion ("New Program" before "Visitors", followed by "Normal Cases") is just a tie-breaker.
    Based on my understanding of the code you provided, this person is being excluded altogether because they do not have a record that evaluates to rnum = 1.ROW_NUMBER never returns a value of 2 or 3 unless it has already returned a value of 1. (At least that's how it's supposed to work, and I've never heard of any bugs concerning it.)
    This record is also complicated because it has two terms, Does "term" mean "academic_period" here?
    in all cases, we would want to select the highest term and then if there is still more than one qualifying record, base the "tie breaker" on the cases. Does this make sense or is my explanation still unclear?It's unclear.
    Maybe you need to add one more line at the beginning of the analytic ORDER BY clause (the 6th line below):
    WITH     got_r_num     AS
         SELECT     m.*
         ,     ROW_NUMBER () OVER ( PARTITION BY  id
                             ORDER BY       
                                             academic_period     DESC,          -- Added
                                             CASE
                                       WHEN  primary_program_ind      = 'N'     --Existing Students who have a new program (Continuing Law and added Business)
                                                       AND   academic_period_admitted      = academic_period
                                                       AND   student_population       != 'V'
                                                       AND   program                is not null
                                            THEN 1
                                                    WHEN  primary_program_ind      = 'Y'     --Visitors (Each term considered new)
                                                       AND   student_population      = 'V'
                                                       AND   academic_period_admitted is not null
                                            THEN 2
                                                    WHEN  primary_program_ind      = 'Y'     --Normal Cases
                                                   AND   academic_period_admitted is not null
                                            THEN 3
                                             END
                           )     AS r_num
         FROM     multirows     m
    --     WHERE     ...     -- If you need any filtering, this is where it goes
    SELECT     *     -- or list all columns except r_num
    FROM     got_r_num
    WHERE     r_num     = 1
    ;

  • Info Records Per Material Group Standard Report Not Running at All.

    Hi Experts,
    We had a Small problem Where while Running Info Records Per Material Group(T-code ME1W ) Standard Report the Report is not Showing any output in PRD, where else running Info Records Per Material (T-Code ME1M ) Standard Report the Output is getting Displayed.
    Our System is Currently SAP EEC 6.0 & Application Package SAP_APPL is of release 604     & Level 0007, Highest Support Package is SAPKH60407.
    is this Issue covered in Some OSS Note?
    Thanks & Regards
    Priyesh Shah

    Hi,
    The info-records for the materials which appears in the standard report ME1M/ME1L is different from the one which appear in ME1W.
    If you try with the material groups of the ME1L or ME1M info-records it wont be displayed in ME1W.
    ME1W will display only the info-records which are created @ material group level.
    i.e. try to create a new info-record using ME11 without entering material, in the general data screen you have to enter the material group & other parameters.
    Now once you save this info-record,same will appear in ME1W.
    Hope its clear.
    Thanks & Regards,

  • Can any one tell me how to select latest record

    Hi,
    Can any one tell me how to select latest record. Below is the requirement
    select * from a where a_Date=v_date.
    out of thousand records with matched condition i need to select latest record
    Thanks in advance

    user12852882 wrote:
    Can any one tell me how to select latest record. Below is the requirement
    select * from a where a_Date=v_date.
    out of thousand records with matched condition i need to select latest recordHow do you determine the "latest" row? From your description it sounds like the following SQL will define the latest:
    select max(a_date) from aThis will return the last/latest date used from the table.
    Secondly, you now want to select the last row - or rows. As a_date may not be a primary key (you did not state it was and usually a date column make poor choice as unique identifier), there could be more than one row with that "+latest date+".
    So to find the latest row(s):
    select * from a where a_date = (select max(a_date) from a)Or you could do the following:
    declare
      latestDate date;
    begin
      // find the latest date and store it for use and re-use
      select max(a_date) into latestDate from a;
      // now process the last row(s) - and consider rewriting this
      // as a bulk processing loop
      for c in (select * from a where a_date = latestDate)
      loop
        .. do something with the row
      end loop;
      // now use latestDate variable for some other
      // required processing
    .. code goes here ...
    end;

  • How we can select two records in alv report

    how we can select two records in alv report

    Hello,
    You can use the method <b>get_selected_rows</b>.
         CALL METHOD gv_alv->get_selected_rows
            IMPORTING
          ET_INDEX_ROWS =
            et_row_no     = lt_selected_rows.
    READ TABLE lt_selected_rows INTO ls_selected_row INDEX 1 .
    The table <b>lt_selected_rows</b> will contain all the selected rows.
    Regards,
    Beejal
    **reward if this helps

  • Top 2 records per employee ID

    I am trying to retrieve the top two salary records per employee ID to show their current salary and one previous. The salary table is a transaction type table showing all salary changes per employee.
    For example:
    Employee_ID
    Salary_Effective_Date
    Salary_Amount
    We are using Oracle 10G, SQLPlus. We normally select the max(salary_effective_date) to get their current salary_amt. Is there anyway to pull the top two per employee to get current and previous?

    Hi,
    This question doesn't concern SQL*Plus or iSQL*Plus in any way, does it? It's a SQL question, so, in the future, you might have better luck posting questions like this in the SQL forum:
    PL/SQL
    The analytic RANK (or, depending on how you want to handle ties, ROW_NUMBER) function is more versatile than aggregate functions for this kind of thing
    Since I don't have a version of your table, I'll use the scott.emp table to illustrate.
    Here's one way to get some information about the two latest rows (in order by hiredate) for each job:
    WITH     got_r_num     AS
         SELECT     job, hiredate, ename, sal
         ,     RANK () OVER ( PARTITION BY  job
                          ORDER BY      hiredate     DESC
                        )     AS r_num
         FROM     scott.emp
    SELECT       *
    FROM       got_r_num
    WHERE       r_num     <= 2
    ORDER BY  job
    ,       hiredate     DESC
    ;Output:
    JOB       HIREDATE  ENAME             SAL      R_NUM
    ANALYST   19-APR-87 SCOTT            3000          1
    ANALYST   03-DEC-81 FORD             3000          2
    CLERK     23-MAY-87 ADAMS            1100          1
    CLERK     23-JAN-82 MILLER           1300          2
    MANAGER   09-JUN-81 CLARK            2450          1
    MANAGER   01-MAY-81 BLAKE            2850          2
    PRESIDENT 17-NOV-81 KING             5000          1
    SALESMAN  28-SEP-81 MARTIN           1250          1
    SALESMAN  08-SEP-81 TURNER           1500          2 
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the results you want from that data.
    Explain, using specific examples, how you get those results from that data.

  • HOW TO PRINT ONE RECORD PER ONE PAGE

    Hi I have report , with two queries. Each query has one group with the same data. lets say the queries are Q1 and Q2. The Groups are with column DeptNo, and DeptNo1 both pointing to the same column DEPTNO. Now I want to design it in such a manner that it shoudl print each group , one record per page, but same group on the same page. For Example
    ON PAGE 1
    DpetNo 10
    Emp1
    Emp2
    Emp3
    DeptNo1 10
    Emp1
    EMp2
    Emp3
    ON PAGE 2
    DeptNo 20
    Emp4
    Emp5
    DeptNo1 20
    Emp4
    Emp5
    ON PAGE 3
    DeptNo 30
    Emp6
    Emp7
    Emp8
    DeptNo1 30
    Emp6
    Emp7
    Emp8
    How the lay our will be ? What will be the conditions. I can set the property in each group to print one record per page. But how to make it so that it will print like above.
    Thanks
    FEROZ

    Hi Feroz,
    You can create a query Q0 to return DeptNo 10, DeptNo 20..... and make it as the parent of Q1 and Q2. Then you can print one dept per page.
    Regards,
    George

  • Select "most recent" records in abap

    Hi
    how can I select the most recent records in a table by using the abap select statement.
    Example: The 100 rows with the "highest" (most recent) sequence-numbers in a table with documents.
    somehow like this:
        SELECT "most recent" * FROM draw
        INTO TABLE gt_doklist
        UP TO 100 ROWS
        where ...
    Has anybody an idea?
    Thanks in advance,
    Willi

    Actually I believe that all the answers are wrong.
    I believe that there will never be a single statement. If you need to determine the last 100 records for a special user you first need to determine the highest document number.
    this can be done by
    select max( document_number ) into document_number from table where username = username.
    Any descending sorting order or group by etc. will never make sure that you get the last one. For a simple reason What should the select statement look like that makes sure (in combination of any cursor applied)? Its impossible!
    If you now need the latest 100 records for a single user its the same problem like buffered number ranges. There is no way to perform that task because there is no database routine or sql statement to do so. And 1.5 million records are too much to try out or select everything.
    You could do an assumption that the last 100 for that user have been posted during the last 1000 or last 10.000 records, select them and filter out.
    Alternative you can perform the following select statement for 100 times. Using an index on document number and user might not be such a performance killer if its only done for one user during his online dynpro process:
    data: max_number type char10.
    select max( documentnumber ) into max_number from table
      where username = username into [structure].
    max_number = max_number + 1.
    do 100 times
    select max( documentnumber ) from table intomax_number
      where username = username and docnumber lt max_docnumber.
    select * from [db_table] into [structure] where docnumber = max_number.
    append [structure] to [table].
    enddo.
    Of course that just draft coding... apply if statements and so on...
    Even though its pretty poor, its the only way to do. Any select statement will never garantee what records you will get if you do not restrict accordingly and if the restriction has to be made on document number, but if there is no way to get the max_number - [100 last records of this user], there is no solution using one statement.
    Thats it.
    Edited by: Rob Burbank on Feb 25, 2010 8:52 AM

  • Report the latest  event (record) for a device

    I could have sworn I had this one working before but for the life of me I cant remember how I did it and I cant seem to figure it out anew.
    I'm tracking events per device. A device may have any number of events in a given time period. I need to track the MOST RECENT event for a device per device. I do not want to have multiple records per device, only the record with the MOST RECENT timestamp.
    I made the following two attempts but I'm still getting nowhere.
    select
      device,
      MAX(dt) KEEP (DENSE_RANK FIRST ORDER BY dt) as time_Var
    from db_table partition (pPname)
    where
        Lower(example) like '%example text%'
        and dt > sysdate - 5and
    select DISTINCT
    device,
           (select TO_CHAR( (MAX(table_name.dt)), 'HH24:MI:SS MM/DD/YYYY') "timeVar"
              from table_name partition (pPName)
              where
           Lower(Example) like '%example text%'
           and dt > sysdate - 5)
    from table_name partition (pPName)
    where
        Lower(Example) like '%example text%'
        and dt > sysdate - 5
    order by device Asc;

    Hi,
    Salim's solution with
    KEEP (DENSE_RANK FIRST ORDER BY dt)will show you the least recent event in the last 5 days.
    If you want the most recent event, change "FIRST" to "LAST"
    KEEP (DENSE_RANK LAST ORDER BY dt)or sort in DESCending order:
    KEEP (DENSE_RANK FIRST ORDER BY dt DESC)If you want to display several columns from the most recent row, you'll have to use KEEP (DENSE_RANK ...) on each of them (except device).
    In that case, you might find it easier to use an analytic function, such as ROW_NUMBER:
    WITH     ranked_data  AS
         SELECT     device, column_a, column_b, column_c
         ,     ROW_NUMBER () OVER ( PARTITION BY  device
                                   ORDER BY          dt     DESC
                           )  AS r_num
         FROM     your_table
         WHERE     LOWER (example)      LIKE '%example text%'
         AND     dt               > SYSDATE - 5
    SELECT  device, column_a, column_b, column_c
    FROM     ranked_data
    WHERE     r_num   = 1;

  • Data Merge: Cannot get multiple records per page

    I am working with a client who is trying to do a directory in Indesign. There are about 1,800 people with information like address, title, employer, phone, etc. This info is on an Excel spread sheet. I made a text, tab delimited and a CSV file from the spreadsheet. I set up a two column text box on each page and want these entries to fill the columns. I am only able to get one person's information per page. Multiple records per page yields no different result. I also had the multiple records option grayed out on a couple tries. I have tried this many times, even tried setting up a simple spread sheet with 9 items. No luck. HELP! I'm brand new to this feature.
    Chris

    the data merge function in indesign doesn't make "next record" merges  like word does, but instead merges to fields within fixed text boxes, so  one frame = one data merge result. when doing mailing labels in word,  there is a field called "next record" which then calls in the next piece  of information.
    the "next record" field is a vital field which indesign doesn't have and  i'd like… but that doesn't answer your question. i can see four ways  of doing what you want to do:
    1) do a mail merge in word and use the "catalog" feature and do the  merge in word. format the word file appropriately using stylesheets, and  once the merge is made, save the file and close it. THEN, place the  file in indesign and then change the imported stylesheets into something  which resembles more like what you want.
    2) use indesign's data merge but make sure that multiple record  layout is selected in the first dialog box when creating merged  document; and that when previewing the records, the records appear to be  in one column (even though they are still in separate text frames).  merge the document, and in the new document, select all the text frames  in the page and then run the MergeTextframes_ID.jsx script which can be  found at http://ajarproductions.com/blo…..-indesign/ .this  will have to be done page by page and then rethreaded each page, but  it's a workaround
    3) if the data in the datamerge is a csv, convert the csv to xml. if  the csv is small (less than 100K) there is a converter online where the  contents of the csv is copied into the converter. it is at http://www.creativyst.com/Prod/15/ . The next step is complicated and needs some knowledge of XML. my  advice is to get hold of a book called "Designer's Guide to Adobe   InDesign and XML" by James Maivald, and specifically read chapter seven  and base your merge on this.
    4) visit the third party providers link within the indesign page of the adobe site and have a look at products marketed there... i think teacup software and cacidi software sell products which do more advanced merges within indesign. they're not free though but are designed to handle big catalogues.
    hope that helps.
    colly

Maybe you are looking for