views:

57

answers:

2

I have a table; let it be called table1; with the following fields and data

alt text

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

How could this be done using SQL queries ?

+4  A: 

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:

Quassnoi
Thanks Quassnoi. The first one returns an extra "rn" column, please edit it as follows: ...... WITH q AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY field2 ORDER BY field3 DESC) AS rn FROM table1) SELECT Field1, Field2, Field3, Field4 FROM q WHERE rn = 1 ...... but the second is great, also the article is great. Many thanks.
Ashraf Bashir
A: 

My go:

SELECT t1.Field1
, t1.Field2
, MAX(t1.Field3)
, t1.Field4
FROM table1 t1
GROUP BY t1.Field2
Carl Bullard
I think that will result in an error (I did not actually try to run it), you are selecting `t1.Field1` but not including it in the `GROUP BY`
KM
Doh, you are correct! Thanks
Carl Bullard
As KM commented, it throws the following error ..... Column 'table1.Field1' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause ..... But anyway Thanks Carl for your answer. Thanks KM for your comment and clarification
Ashraf Bashir