LOC H. answered 03/16/22
20+ years of proficiency in Java, SQL, Python, C#, Algorithms
There are a lot of ways to implement your SQL. You did not mention your database type so I am giving you a solution that uses SQL ANSI ( Work with all database types )
SELECT A.ServiceID, COUNT(*) AS TotalComment,
(
SELECT CommentDetails
FROM ServiceComment B
WHERE B.ServiceID = A.ServiceID
AND B.CommentDate =
(
SELECT MAX(CommentDate) FROM ServiceComment C WHERE C.ServiceID = B.ServiceID
)
) AS LastComment
FROM ServiceComment A
GROUP BY A.ServiceID
Some comments:
- Because you need to get total comments per service -> It means you need to use GROUP BY.
- Because you need to get last comment per service -> You need to query MAX(CommentDate) for each Service, then query the last comment based on the max comment date.