Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Suppose i have 3 tablesAnimal-AnimalId-AnimalNameAnimal_Comment-AnimalId-CommentIdComment-CommentId-Comment-CreatedAtA single animal can have multiple commentsMy SQL query isselect Animal.AnimalId,Animal.AnimalName,Comment.Commentinner join Animal_Comment AC on AC.AnimalId=Animal.AnimalIdinner join Comment C on C.CommentId=AC.CommentIdIs it possible to have a query which will give me a single latest comment for the animal
TG
Master Smack Fu Yak Hacker
6065 Posts
Posted - 2009-09-09 : 15:16:52
Here's one way:
select a.AnimalId ,a.AnimalName ,c.Commentfrom animal aouter apply ( select top 1 c.comment from Animal_Comment ac inner join Comment C on C.CommentId = ac.CommentId where ac.AnimalId = a.AnimalId order by c.createdAt desc ) c