using group by and maximum
I have a post table and postcontent table.
Each time post is edited,an entry is added to postcontent table .
On each such time a filed called version will be incremented by 1 In the postcontent table.
How can I fetch PostId, fr开发者_运维技巧om post able and [Description] from to postcontent table Where version for each post is maximum Ie group by post id ie i am expecting one raw for each post such that it is the 'maximum of version' for the post
select P.PostID,
PC.[Description]
from Post as P
inner join
(
select PostID,
[Description],
row_number() over(partition by PostID order by [Version] desc) as rn
from PostContent
) as PC
on P.PostID = PC.PostID
where PC.rn = 1
SELECT
p.[PostID],
pc.[Description]
FROM
[Post] AS p
INNER JOIN
[PostContent] AS pc
on p.PostID = pc.PostID
WHERE
pc.[Version] = (SELECT MAX([Version]) FROM PostContent WHERE PostID = p.PostID)
I think u have the PostId
in PostContent
table as a foreign key and you want to retrive all the postId
with their Heighest version .
select max(version),PostId from PostContent groupby PostId
精彩评论