给定一个非常简化的包含列的表
Name, Action, Status, Timepoint
1 "A" "Open" "OK" "2012-09-04 10:10:00"
2 "A" "Close" "OK" "2012-09-04 10:05:00"
3 "A" "Close" "ERROR" "2012-09-04 10:02:00"
4 "B" "Look" "NICE" "2012-09-04 10:05:00"
5 "B" "Blow" "COLD" "2012-09-04 10:00:00"
6 "C" "Laugh" "OK" "2012-09-04 10:02:00"
7 "C" "Laugh" "MUTE" "2012-09-04 10:00:00"
如何最有效地为Name和Action组合选择每一行,但只选择最新Timepoint的Action?在上面的示例中,它将返回行
1, 2, 4, 5, 6
工作实现获取行并使用子查询仅在有 0 行具有相同Name和Action组合的较新Timepoint时才返回。但是当数据集变得很大时,这似乎非常低效。是这样的
SELECT Name, Action, Status, Timepoint
FROM foobar
WHERE Name IN (... Names of interest ...) AND
Status IN (... statuses of interest ...) AND
(SELECT COUNT(*) FROM foobar AS t2 WHERE t2.Name = Name AND t2.Status = Status AND t2.Timepoint > Timepoint) = 0
order by Name, Timepoint