We help IT Professionals succeed at work.

SQL Select from 2 tables

248 Views
Last Modified: 2012-06-27
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!
Comment
Watch Question

Guy Hengel [angelIII / a3]Billing Engineer
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2009

Commented:
CERTIFIED EXPERT
Top Expert 2010
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Scott PletcherSenior DBA
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019

Commented:
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

Author

Commented:
Thank you this worked well
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.