Return row with the max value of one column per group(返回每组一列最大值的行)
问题描述
如果不搜索同一个表至少两次以获取最大行,然后获取该行的值,我就很难做到这一点.有问题的桌子很大,所以这是不可接受的.
I am having a hard time doing this without searching the same table at least twice in order to grab the max row, and then grab the value for that row. The table in question is quite big so this is unacceptable.
这是我的桌子可能的样子:
Here is what my table might look like:
SCORES
ID ROUND SCORE
1 1 3
1 2 6
1 3 2
2 1 10
2 2 12
3 1 6
我需要返回每个 ID 在最近一轮中获得的分数.也就是说,有最大(回合)但不是最大分数的那一行.
I need to return the score that each ID got in the most recent round. That is, the row with the max (round), but not the max score.
OUTPUT:
ID ROUND SCORE
1 3 2
2 2 12
3 1 6
现在我有:
SELECT * FROM
(SELECT id, round,
CASE WHEN (MAX(round) OVER (PARTITION BY id)) = round THEN score ELSE NULL END score
FROM
SCORES
where id in (1,2,3)
) scorevals
WHERE
scorevals.round is not null;
这行得通,但效率很低(我必须手动过滤掉所有这些行,而我一开始就应该无法抓取这些行.)
This works, but is pretty inefficient (I have to manually filter out all of these rows, when I should just be able to not grab those rows in the first place.)
我该怎么做才能获得正确的值?
What can I do to get the right values?
推荐答案
这也可以不使用子查询:
This is also possible without subquery:
SELECT DISTINCT
id
,max(round) OVER (PARTITION BY id) AS round
,first_value(score) OVER (PARTITION BY id ORDER BY round DESC) AS score
FROM SCORES
WHERE id IN (1,2,3)
ORDER BY id;
完全返回您要求的内容.
关键是 DISTINCT 应用在 窗口函数之后.
Returns exactly what you asked for.
The crucial point is that DISTINCT is applied after window functions.
SQL 小提琴.
也许更快,因为它两次使用同一个窗口:
Maybe faster because it uses the same window twice:
SELECT DISTINCT
id
,first_value(round) OVER (PARTITION BY id ORDER BY round DESC) AS round
,first_value(score) OVER (PARTITION BY id ORDER BY round DESC) AS score
FROM SCORES
WHERE id IN (1,2,3)
ORDER BY id;
否则做同样的事情.
这篇关于返回每组一列最大值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回每组一列最大值的行
基础教程推荐
- 是否可以执行按位分组功能? 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 无法解决整理冲突 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
