table1
;包含以下字段和数据
alt text http://img228.imageshack.us/img228/3827/45939084.png
我需要一个查询,为Field3
中具有相同值的每组记录返回Field2
中最大值的记录。这样查询返回:
alt text http://img87.imageshack.us/img87/62/48847706.png
如何使用SQL查询完成此操作?
答案 0 :(得分:5)
此:
WITH q AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY field2 ORDER BY field3 DESC) AS rn
FROM table1
)
SELECT *
FROM q
WHERE rn = 1
或者这个:
SELECT q.*
FROM (
SELECT DISTINCT field2
FROM table1
) qo
CROSS APPLY
(
SELECT TOP 1 *
FROM table1 t
WHERE t.field2 = qo.field2
ORDER BY
t.field3 DESC
) q
根据field2
基数,第一个或第二个查询可以更有效。
有关详细信息,请参阅此文章: