How to retrieve the rows (with maximum value in a field) having a another common field?
I have a table; let it be called table1
; with the following fields 开发者_如何学Pythonand data
alt text http://img228.imageshack.us/img228/3827/45939084.png
I need a query that returns the record with the maximum value in Field3
for each group of records having the same value in Field2
. So that the query returns:
alt text http://img87.imageshack.us/img87/62/48847706.png
How could this be done using SQL queries ?
This:
WITH q AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY field2 ORDER BY field3 DESC) AS rn
FROM table1
)
SELECT *
FROM q
WHERE rn = 1
or this:
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
Depending on the field2
cardinality, the first or the second query can be more efficient.
See this article for more details:
- SQL Server: Selecting records holding group-wise maximum
精彩评论