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. 

Similar Messages

  • 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

  • Maximum records per page

    Hi, I would like to is there any way to set the maximum records per page dynamically?
    For eg. If report_type = '1' then maximum records = 3
    If report_type = '2' then maximum records = 1
    Please help and thank you very much!

    Hi Shiau Chin,
    I don't think you can change maximum records per page property at run time. What you can do is:
    Create another repeating frame for the same data group and set maximum records per page property for first repeating frame as 2 and 3 for second repeating frame and in format trigger of these repeating frames show or hide these frames based on report type.
    Thanks

  • How to Control with Maximum Record per Page

    Hi Every one
    how can I control with maximum record per page with parameter sending from Form
    ex.
    if I set parameter with value=15 the report will run 15 rows per page ?
    Can anyone help me Please ASAP ?
    Thankx

    PLay around with SRW.SETMAXROW , from memory that should do the trick.
    Cheers.
    N.

  • Maximum records per page is not working

    I am trying to run a report with the property on repeating frame which says
    MAXIMUM RECORDS PER PAGE. I set it to 20 and also set property PRINT OBJECT ON = 'ALL PAGES' still when report is in preview mode it is not displaying more then 20 records. I know this query has more then 30 records.
    If anybody has any idea let me know.

    Asit,
    If you only want to have a maximum of 20 records per page, you only need to set the maximum records per page property. You should leave the print object on property at default or first. For a further explanation of how the print object on property works, check out the on-line help at http://otn.oracle.com/reports/help/. There is a section on restrictions which may make this clearer for you.
    Hope that helps,
    Toby

  • 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

  • Limit number of records per page in RDF report

    Hi Alll,
    My rdf report query return 200 records but while prinitng on the paper i should restrict 60 records perpage... please help me on how should i do it...
    Thanks in advance

    Though the maximum records per page while prinitng it is printing continously on the paper...

  • SQL Loader-704: Internal error: Maximum record length must be = [10000000]

    Hi,
    running SQL*Loader (Release 8.1.7.2.1) causes an error "SQL*Loader-704: Internal error: Maximum record length must be <= [10000000]". This error occurs when SQLLoader is trying to load several thousand records into a database table. Each record is less than 250 bytes in length.
    Any idea what could cause the problem?
    Thanks in advance!
    Ingo
    And here's an extract from the log file generated by SQLLoader :
    Number to load: ALL
    Number to skip: 0
    Errors allowed: 50
    Bind array: 1360 rows, maximum of 10485760 bytes
    Continuation: none specified
    Path used: Conventional
    Table "SYSTEM"."BASICPROFILE$1", loaded from every logical record.
    Insert option in effect for this table: APPEND
    TRAILING NULLCOLS option in effect
    Column Name Position Len Term Encl Datatype
    UUID FIRST * O(X07) CHARACTER
    DOMAINID NEXT * O(X07) CHARACTER
    LASTMODIFIED NEXT * O(X07) DATE DD/MM/YYYY HH24:MI:SS
    ANNIVERSARY NEXT * O(X07) CHARACTER
    BIRTHDAY NEXT * O(X07) CHARACTER
    COMPANYNAME NEXT * O(X07) CHARACTER
    DESCRIPTION NEXT * O(X07) CHARACTER
    FIRSTNAME NEXT * O(X07) CHARACTER
    COMPANYNAMETRANSCRIPTION NEXT * O(X07) CHARACTER
    FIRSTNAMETRANSCRIPTION NEXT * O(X07) CHARACTER
    GENDER NEXT * O(X07) CHARACTER
    HOBBIES NEXT * O(X07) CHARACTER
    HONORIFIC NEXT * O(X07) CHARACTER
    JOBTITLE NEXT * O(X07) CHARACTER
    KEYWORDS NEXT * O(X07) CHARACTER
    LASTNAME NEXT * O(X07) CHARACTER
    LASTNAMETRANSCRIPTION NEXT * O(X07) CHARACTER
    NICKNAME NEXT * O(X07) CHARACTER
    PREFERREDLOCALE NEXT * O(X07) CHARACTER
    PREFERREDCURRENCY NEXT * O(X07) CHARACTER
    PROFESSION NEXT * O(X07) CHARACTER
    SECONDLASTNAME NEXT * O(X07) CHARACTER
    SECONDNAME NEXT * O(X07) CHARACTER
    SUFFIX NEXT * O(X07) CHARACTER
    TITLE NEXT * O(X07) CHARACTER
    CONFIRMATION NEXT * O(X07) CHARACTER
    DEFAULTADDRESSID NEXT * O(X07) CHARACTER
    BUSINESSPARTNERNO NEXT * O(X07) CHARACTER
    TYPECODE NEXT * O(X07) CHARACTER
    OCA NEXT * O(X07) CHARACTER
    SQL*Loader-704: Internal error: Maximum record length must be <= [10000000]

    As a second guess, the terminator changes or goes missing at some point in the data file. If you are running on *NIX, try wc -l data_file_name.  This will give a count of the number of lines (delimited by CHR(10) ) that are in the file.  If this is not close to the number you expected, then that is your problem.
    You could also try gradually working through the data file loading 100 records, then 200, then 300 etc. to see where it starts to fail.
    HTH
    John

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

  • Maximum Number of record Per page using XML Publisher with RTF template

    Hi
    I am creating customer statement and want to show only 20 records per page. How we can set maximum number of repord per page in rtf template.
    Thanks
    Ravi

    Ravi,
    I hope you are already done with this. In the invoice there is a nice example you can use on the xml blogs.
    You limit the number of lines per page when you use the xsl commands like this in your template:
    <xsl:variable name="lpp" select="number(13)"/>
    <?for-each@section:LIST_G_INVOICE?>
    <xsl:variable xdofo:ctx="incontext" name="invLines" select=".//G_LINES[LINE_TYPE='LINE']"/>
    <?for-each:$invLines?> <?if:(position()-1) mod $lpp=0?> <xsl:variable name="start" xdofo:ctx="incontext" select="position()"/>
    and then you have the table where you have the data
    <?for-each:$invLines?><?if:position()>=$start and position()<$start+$lpp?>
    and all your lines
    and then
    <?end if?><?end for-each?>

  • Can we change [maximum number of records per page] property at run time

    can we change [maximum number of records per page] property at run time in report 6i

    Ravi,
    I hope you are already done with this. In the invoice there is a nice example you can use on the xml blogs.
    You limit the number of lines per page when you use the xsl commands like this in your template:
    <xsl:variable name="lpp" select="number(13)"/>
    <?for-each@section:LIST_G_INVOICE?>
    <xsl:variable xdofo:ctx="incontext" name="invLines" select=".//G_LINES[LINE_TYPE='LINE']"/>
    <?for-each:$invLines?> <?if:(position()-1) mod $lpp=0?> <xsl:variable name="start" xdofo:ctx="incontext" select="position()"/>
    and then you have the table where you have the data
    <?for-each:$invLines?><?if:position()>=$start and position()<$start+$lpp?>
    and all your lines
    and then
    <?end if?><?end for-each?>

  • Page Break / Maximum Rows per Page

    Hi - One more question....
    I have a group left report and want to keep each master group (the value that is grouped on the left) on its own separate page. In Reports 6i I would have set the Max Rows Per Page property to 1 on the outer repeating frame and that would make sure I had at most 1 master record per page.
    The only way I can see to replicate that functionality in XML Pub is to insert a page break (split-by-page-break) before the end-for-each tag on the group. It looks good in PDF, but in Excel or HTML it repeats the full header with Logo and titles and looks pretty ridiculous.
    So the $1 Million dollar question is how can I make sure there is at most 1 master group per page, but when I output to Excel I only get the header once? Because if I take out the split-by-page-break I get the desired output in Excel but not in the PDF. I really want to be able to use 1 template for all output types because it seems silly to have a separate template depending on the output type.
    Ideas?

    PDF, understand what is page,
    HTML is a single page view and it does nto understand, and same is the case for Excel.

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

  • REPORT BUILDER: MAX. NUMBER OF RECORDS PER PAGE

    Dear Consultant,
    Using DEVELOPER 2000 R2.1 REPORT BUILDER, is there any way to set the " MAXIMUM NUMBER OF RECORDS PER PAGE" dynamically by user input when calling the report, without the need to modify the report at Design time and recompile it?
    Thanks for your help.
    Ghia Haidar
    Developer
    Astrolabe IT - Professional Consultants
    Beirut, Lebanon
    Phone: + 961 1 841.050
    Fax: + 961 1 841.055 www.astrolabe.com.lb
    null

    Refer Manish question.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Ali DHAINI ([email protected]):
    Dear Consultant,
    Using DEVELOPER 2000 R2.1 REPORT BUILDER, is there any way to set the " MAXIMUM NUMBER OF RECORDS PER PAGE" dynamically by user input when calling the report, without the need to modify the report at Design time and recompile it?
    Thanks for your help.
    Ghia Haidar
    Developer
    Astrolabe IT - Professional Consultants
    Beirut, Lebanon
    Phone: + 961 1 841.050
    Fax: + 961 1 841.055 www.astrolabe.com.lb
    <HR></BLOCKQUOTE>
    null

  • Data Merge, its is possible to display 5 records per page?

    I have no problem doing data merges.  They always seem to only show one record per page, but is there a way to be able to display more records per page?

    Read the help for a full explanation, then come back here with specific questions if you still have problems...
    Basically, you set up a single instance of field placeholders on you page, then select multiple records per page in the merge options. You cannot specify a number directly, but ID will reprduce as many records on the page as all elements will fit using the spacing settings you set up, so you might want to add an empty frame the size required to get your five instances with zero spacing and group it with the field tags.

Maybe you are looking for

  • Intel iris problem

    I Badly Want to install intel Iris but it says its not validated for the product what should i do someones told me to install it mannualy but what is the downside of that My laptop Sattelite L40-A with specs Intel Core i5 3427U @ 1.80GHz Ivy Bridge 2

  • Change of Payment Term

    Hi All, 1. I think we can change the payment term assigned to the vendor (in master data) while posting the invoice, please confirm if I am correct? 2. Is it possible to change the payment term in the document before the payment either in case of man

  • Schedule report

    hi... I would like to know how to schedule reports in BO.My requirement is that the reports are run every month through out the year.we tried to bring the date from BW side but due to too many prompts and other factors it dint work.so how can the sys

  • Package and the transport number for Parameter id

    Hi , Based on a posting earlier to create a Parameter id , wanted to know what is is the best practice to fill in the PACKAGE NAME while creating a Parameter id in SM30 table TPARA?

  • Printing From Powerbook to HP on WindowsXP Workgroup

    I am new to the Mac world. I have an XP network. My new powerbook connects fine. I have followed the instructions posted by iFelix in another thread about how to connect. I see the printer, I connect to the printer. When I go to print, however, I get