Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

SQL seleziona max(data) e il valore corrispondente

Puoi usare una sottoquery. La sottoquery otterrà il Max(CompletedDate) . Quindi prendi questo valore e ti unisci nuovamente al tuo tavolo per recuperare la nota associata a quella data:

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