Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT DISTINCT TOP 5 in SQL Server

I can't get this sql query right...

I want the top 5 latest comments from tblComment. The problem is that I get more then one comment with the same ProductID. I don't want that.

SELECT DISTINCT TOP 5
   tblProduct.ProductID, 
   tblProduct.ProductName, 
   tblComment.DateAdded
FROM   
    tblComment 
INNER JOIN 
    tblProduct ON tblProduct.ProductID = tblComment.ProductID
ORDER BY 
    tblComment.DateAdded DESC

What am I doing wrong?

like image 277
user1007103 Avatar asked Mar 09 '26 19:03

user1007103


1 Answers

Assuming your comment table has an id field try this:

SELECT TOP 5

tblProduct.ProductID, 
tblProduct.ProductName, 
tblComment.DateAdded

FROM   tblComment 
JOIN   tblProduct ON tblProduct.ProductID = tblComment.ProductID
JOIN   (Select ProductID, max(id) as maxid From tblComment Group By ProductId) t on tblComment.id = t.maxid 

ORDER BY tblComment.DateAdded DESC
like image 158
brendan Avatar answered Mar 11 '26 09:03

brendan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!