I have two tables that I am outer joining together: “Post” left outer join with “Comments”.
There is a one-to-many relationship between Post and Comments.
I would like to be able to pull the first, say 10, Post records and all of the associated Comments (if any) for each Post.
The way I would usually do this would be to have a Common Table Expression and use ROW_NUMBER() OVER. However, ROW_NUMBER() counts each row, which in this case would not work since I only want to count the Post records.
I was looking at ROW_NUMBER() OVER (PARTITION), but it does not work how I would expect it.
So if want the first 5 Posts, I would get something like:
PostNumber PostId CommentId
1 1 1
1 1 2
2 2 -
3 8 3
3 8 4
4 9 5
5 15 -
Have a look at using DENSE_RANK function
Something like