我有一张这样的表
ProjectID PhaseID Comment CommentDate
1 1 a 2/15/2014
1 1 b 5/1/2014
1 2 c 8/15/2014
1 2 d 1/1/2015
2 1 e 1/21/2014
2 2 f 5/15/2014
2 2 g 1/1/2015
我如何获得每个阶段的每个项目的最新(前1)评论?例如,对于项目1,阶段1,我应该得到“b”和“5/1/2014”
谢谢!
答案 0 :(得分:2)
select ProjectID,PhaseID,Comment,CommentDate from
(select row_number() over(partition by Project_ID,PhaseID order by CommentDate desc) as rn,* from table) a
where a.rn = 1
答案 1 :(得分:0)
这种类型的查询在有标识列时效果最好(并且值总是按顺序插入)但是这样可以得到你需要的东西,假设没有重叠的评论日期
select t.*
from table t
inner join (
SELECT max(commentDate) as maxDate,
phaseId,
projectId
FROM table
group by phaseId, projectId
) maxComments on t.phaseId = maxComments.phaseId
and t.projectId = maxComments.projectId
and t.commentDate = maxComments.maxDate