我有一张桌子:
id|val|updated
1 | 31|2012-01-12
1 | 34|2012-01-15
2 | 41|2012-01-15
3 | 44|2012-01-15
4 | 66|2012-01-01
我需要选择具有最大更新值的id和val。 所以对于这个表,结果应该是:
1| 34| 2012-01-15
2| 41| 2012-01-15
3| 44| 2012-01-15
4| 66| 2012-01-01
答案 0 :(得分:6)
这需要在针对主表连接的子查询中使用MAX()
聚合。
SELECT
tbl.id,
tbl.val,
tbl.updated
FROM tbl JOIN (
/* Subquery gets MAX(updated) per id to JOIN against */
SELECT
id,
MAX(updated) as updated
FROM tbl
GROUP BY id
) t2 ON tbl.id = t2.id AND tbl.updated = t2.updated
答案 1 :(得分:3)
其他几种“便携式”方法。在我对SQL SERVER 2008的快速测试中,Michael的查询表现最佳
SELECT T1.*
FROM yourTable AS T1
WHERE NOT EXISTS(
SELECT *
FROM yourTable AS T2
WHERE T2.id = T1.id
AND T2.updated > T1.updated
)
SELECT T1.*
FROM yourTable AS T1
LEFT JOIN yourTable AS T2 ON
(
T2.id = T1.id
AND T2.updated > T1.updated
)
WHERE T2.id IS NULL
答案 2 :(得分:1)
选择的答案可以正常工作,但这是一个更快的解决方案。它不使用连接是可以减慢查询速度的组。这个使用比组和连接快得多的分区。看看:
select id, val, Maxdate as updated from
(
select id, val,
Max(updated) over(partition by id order by updated desc) as MaxDate,
Row_Number() over(partition by id order by updated desc) as RowNumber,
from table1
)
where RowNumber = 1