Query to bring back a record with the highest date from a column

  • Hi all,

    I have created a query that brings back the following information from tables which puts an end column in where the pupil has more than 1 attendance at a school COUNT(*). This means that I have put in a having clause where this count > 1           

    IDPUP_UPN_DFEEPUP_UPN_DFEE_TEMPF_NAMEM_NAMES_NAMEPER_DOBSCH_DFEESCH_NAMEPAT_FROM_DATEPAT_TO_DATE More_Than_1_Attendace
    108N830 Sara Smith12/06/1991Y152Old Hill school08/09/199931/08/20022
    108N830 Sara Smith12/06/1991Y152Old Hill school06/01/200331/08/20032
    142U830 TraceyRoseAustin31/06/1993Y152Old Hill school05/09/200031/08/20022
    142U830 TraceyRoseAustin31/06/1993Y152Old Hill school16/06/200431/08/20042

    The above is just a sample of two pupils. I then want to run a query that only brings back the record with the highest PAT_TO_DATE.

    For example Sara Smith, the second record is the one that will be brought back.

    I tried a MAX function but couldnt quite get it to work. 

    any help would be fantastic.

    Debbie 

                

  • Something along the lines of the following should work:

    SELECT Y.*

    FROM YourTable Y

     JOIN (

      SELECT Y1.[ID], MAX(Y1.PAT_TO_DATE) AS PAT_TO_DATE

      FROM YourTable Y1

      GROUP BY Y1.[ID]) D

     ON Y.[ID] = D.[ID] AND Y.PAT_TO_DATE = D.PAT_TO_DATE

  • I cannot thank you enough. Its worked perfectly. Although now I need to sort out all those records where there is an open attendance (WHERE PAT_TO_DATE IS NULL) which should be fun.

    I was looking at this in completely the trying way trying to put the MAX in a having clause.

    Thanks again

     

    Debbie

     

  • I cannot thank you enough. Its worked perfectly. Although now I need to sort out all those records where there is an open attendance (WHERE PAT_TO_DATE IS NULL) which should be fun.

    I was looking at this in completely the trying way trying to put the MAX in a having clause.

    Thanks again

     

    Debbie

     

  • I like the OVER clause for this type of problem.

    select * from

    (SELECT *, RANK(PARTITION BY PUP_UPN_DFEE ORDER BY PUP_UPN_DFEE, PAT_TO_DATE DESC) as rn

    FROM TableName

    ) t

    where rn = 1

    Or you can use ROW_NUMBER instead of RANK if you want to make sure you only ever get one row per student.

    Rob Farley
    LobsterPot Solutions & Adelaide SQL Server User Group
    Company: http://www.lobsterpot.com.au
    Blog: http://blogs.lobsterpot.com.au

  • Thanks for that,

    It looks a bit scary,but I will definitely give it a go!

    Debbie

     

     

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply