MySQL 以最大值分组
MySQL group by with max value
嗨,我有这个 table。
id lat lng userId
1 12 23 1
2 45 34 2
3 42 34 3
4 33 34 1
5 36 79 2
6 53 98 2
7 23 90 3
8 23 67 1
这里我们有三个用户。 (用户 ID 1、2、3)。我想获取每个用户的最新记录(id 列最大值)。
我的例外输出是这个
userId lat lng
1 23 67
2 53 98
3 23 90
此查询将按选项给我分组
SELECT
*
FROM
covid.locations
GROUP BY userId;
但是如何将它与 MAX(id)
函数结合起来。
一种方法是使用以下方法:
SELECT
cl.*
FROM covid.locations cl
INNER JOIN (
SELECT
userid
, MAX( id ) mid
FROM covid.locations
GROUP BY
userId
) g ON cl.userid = g.userid
AND cl.id = cl.mid
另一种是使用row_number() over()
SELECT
userId
, lat
, lng
FROM (
SELECT
*
, ROW_NUMBER() OVER (PARTITION BY userid ORDER BY id DESC) rn
FROM covid.locations
GROUP BY
userId
) d
WHERE rn = 1
两者都将根据 table 的 id
列识别源 table 中的 "most recent" 行。请注意,第二个查询需要 MySQL 版本 8+,因为这是该数据库支持 row_number()
的时候。第一个查询应该 运行 in dbms supporting SQL.
这样就可以了
SELECT
*
FROM
covid.locations
where id in (select max(t.id) from covid.locations t group by t.userId)
order by id desc;
上述查询的示例可以在 SQLFiddle
中找到
嗨,我有这个 table。
id lat lng userId
1 12 23 1
2 45 34 2
3 42 34 3
4 33 34 1
5 36 79 2
6 53 98 2
7 23 90 3
8 23 67 1
这里我们有三个用户。 (用户 ID 1、2、3)。我想获取每个用户的最新记录(id 列最大值)。 我的例外输出是这个
userId lat lng
1 23 67
2 53 98
3 23 90
此查询将按选项给我分组
SELECT
*
FROM
covid.locations
GROUP BY userId;
但是如何将它与 MAX(id)
函数结合起来。
一种方法是使用以下方法:
SELECT
cl.*
FROM covid.locations cl
INNER JOIN (
SELECT
userid
, MAX( id ) mid
FROM covid.locations
GROUP BY
userId
) g ON cl.userid = g.userid
AND cl.id = cl.mid
另一种是使用row_number() over()
SELECT
userId
, lat
, lng
FROM (
SELECT
*
, ROW_NUMBER() OVER (PARTITION BY userid ORDER BY id DESC) rn
FROM covid.locations
GROUP BY
userId
) d
WHERE rn = 1
两者都将根据 table 的 id
列识别源 table 中的 "most recent" 行。请注意,第二个查询需要 MySQL 版本 8+,因为这是该数据库支持 row_number()
的时候。第一个查询应该 运行 in dbms supporting SQL.
这样就可以了
SELECT
*
FROM
covid.locations
where id in (select max(t.id) from covid.locations t group by t.userId)
order by id desc;
上述查询的示例可以在 SQLFiddle
中找到