Link to home
Start Free TrialLog in
Avatar of rdgit
rdgit

asked on

SQL Select from 2 tables

I have a sql query question.
I have 2 tables... Projects and ProjComments

Projects has 2 fields ProjID and ProjName
ProjComments has 4 fields. ProjCommentID, ProjID, CommentDate and Comment

There can be several comments on one project

what sql code would I use to select all projects and only the most recent
comment for each project? Some projects won't have any comments.

so my results would include
ProjID, ProjName,  comment Date and Comment.

thanks!
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

ASKER CERTIFIED SOLUTION
Avatar of Patrick Matthews
Patrick Matthews
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SELECT
    p.ProjID, p.ProjName, pc.CommentDate, pc.Comment
FROM Projects p
LEFT OUTER JOIN (
    SELECT ProjID, CommentDate, Comment,
        ROW_NUMBER() OVER(PARTITION BY ProjID ORDER BY CommentDate DESC) AS row_num
    FROM ProjComments
) AS pc ON
    pc.row_num = 1 AND
    pc.ProjID = p.ProjID
--ORDER BY p.ProjID | ORDER BY p.ProjName
Avatar of rdgit
rdgit

ASKER

Thank you this worked well