title: SQL - Updating records based on most recent date
body: <p>I am having difficulty updating records within a database based on the most recent date and am looking for some guidance. By the way, I am new to SQL.</p>
  
  <p>As background, I have a windows forms application with SQL Express and am using ADO.NET to interact with the database. The application is designed to enable the user to track employee attendance on various courses that must be attended on a periodic basis (e.g. every 6 months, every year etc.). For example, they can pull back data to see the last time employees attended a given course and also update attendance dates if an employee has recently completed a course.</p>
  
  <p>I have three data tables:</p>
  
  <ol>
  <li>EmployeeDetailsTable - simple list of employees names, email address etc., each with unique ID</li>
  <li>CourseDetailsTable - simple list of courses, each with unique ID (e.g. 1, 2, 3 etc.)</li>
  <li>AttendanceRecordsTable - has 3 columns { EmployeeID, CourseID, AttendanceDate, Comments }</li>
  </ol>
  
  <p>For any given course, an employee will have an attendance history i.e. if the course needs to be attended each year then they will have one record for as many years as they have been at the company.</p>
  
  <p>What I want to be able to do is to update the 'Comments' field for a given employee and given course based on the most recent attendance date. What is the 'correct' SQL syntax for this?</p>
  
  <p>I have tried many things (like below) but cannot get it to work:</p>
  
  <pre><code>UPDATE AttendanceRecordsTable
  SET Comments = @Comments
  WHERE AttendanceRecordsTable.EmployeeID = (SELECT EmployeeDetailsTable.EmployeeID FROM EmployeeDetailsTable WHERE (EmployeeDetailsTable.LastName =@ParameterLastName AND EmployeeDetailsTable.FirstName =@ParameterFirstName)
  AND AttendanceRecordsTable.CourseID = (SELECT CourseDetailsTable.CourseID FROM CourseDetailsTable WHERE CourseDetailsTable.CourseName =@CourseName))
  GROUP BY MAX(AttendanceRecordsTable.LastDate)
  </code></pre>
  
  <p>After much googling, I discovered that MAX is an aggregate function and so I need to use GROUP BY. I have also tried using the HAVING keyword but without success.</p>
  
  <p>Can anybody point me in the right direction? What is the 'conventional' syntax to update a database record based on the most recent date?</p>