SQL GROUP BY question
I have a table:
id group data
1 a 10
2 a 20
3 b &n开发者_StackOverflow中文版bsp; 10
4 b 20
I want to get ids of records with max "data" value grouped by "group", i.e.
id
2
4
A more modern answer using CTEs:
;WITH Numbered as (
SELECT ID,ROW_NUMBER() OVER (PARTITION BY group ORDER BY data desc) rn FROM Table
)
SELECT ID from Numbered where rn=1
PostgreSQL has some pretty decent documentation online, look at window functions and WITH queries. In this case, we partition the rows in the table based on which group they belong to. Within each partition, we number the rows based on their data column (with row number 1 being assigned to the highest data value).
In the outer query, we just ask for the rows which were assigned row number 1 within their partition, which if you follow the logic, it must be the maximum data value within each group.
If you need to deal with ties (i.e. if multiple rows within a group both have the maximum data value for the group, and you want both to appear in your result set), you could switch from ROW_NUMBER()
to RANK()
Portable solution:
SELECT T1.id
FROM yourtable T1
JOIN (
SELECT grp, MAX(data) AS data
FROM yourtable
GROUP BY grp
) T2
WHERE T1.grp = T2.grp AND T1.data = T2.data
PostgreSQL solution:
SELECT DISTINCT ON (grp) id
FROM yourtable
ORDER BY grp, data DESC;
PS: I changed the column name from group
to grp
because group
is a reserved word. If you really want to use group
you'll have to quote it.
SELECT Id
FROM Table t1 JOIN (Select Group, Max(Data) Data from Table
group by group) t2
WHERE t1.Group = t2.Group
AND t1.Data = t2.Data
精彩评论