sql >> Base de Datos >  >> RDS >> Sqlserver

SQL seleccione max (fecha) y el valor correspondiente

Puede utilizar una subconsulta. La subconsulta obtendrá el Max(CompletedDate) . Luego toma este valor y se une a su mesa nuevamente para recuperar la nota asociada con esa fecha:

select ET1.TrainingID,
  ET1.CompletedDate,
  ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
  select Max(CompletedDate) CompletedDate, TrainingID
  from HR_EmployeeTrainings
  --where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
  group by TrainingID
) ET2
  on ET1.TrainingID = ET2.TrainingID
  and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID