Search code examples
mysqlsqlclause

Show only the most recent givendate for each record in MySQL


I have the table below with the Patientid, the vaccine name that they received, and the date they received it. I am trying to write an SQL query to only show the most recent given date for each patient.

patientId   vaccinename  givenDate
100          Influenza   7/23/2013
100          Influenza   10/14/2014
101          Influenza   11/24/2009
101          Influenza   10/14/2013
101          Influenza   10/22/2014
102          Influenza   10/24/2013
102          Influenza   10/8/2014

Solution

  • Pretty straightforward, just group by the patient and vaccine and return the max date for the most recent.

    SELECT patientID, vaccinename, MAX(givenDate)
    FROM patient_info
    GROUP BY patientID, vaccinename
    

    SQL Fiddle: http://sqlfiddle.com/#!2/c6eee9/1