Can I use non-aggregate columns with group by?(我可以将非聚合列与 group by 一起使用吗?)
问题描述
您不能(不应该)在 GROUP BY 查询的 SELECT 行中放置非聚合.
You cannot (should not) put non-aggregates in the SELECT line of a GROUP BY query.
然而,我想访问与最大值关联的非聚合之一.用简单的英语,我想要一个表,其中包含各种最旧的 ID.
I would however like access the one of the non-aggregates associated with the max. In plain english, I want a table with the oldest id of each kind.
CREATE TABLE stuff (
id int,
kind int,
age int
);
这个查询给了我我想要的信息:
This query gives me the information I'm after:
SELECT kind, MAX(age)
FROM stuff
GROUP BY kind;
但这并不是最有用的形式.我真的想要与每一行相关联的 id 以便我可以在以后的查询中使用它.
But it's not in the most useful form. I really want the id associated with each row so I can use it in later queries.
我正在寻找这样的东西:
I'm looking for something like this:
SELECT id, kind, MAX(age)
FROM stuff
GROUP BY kind;
输出这个:
SELECT stuff.*
FROM
stuff,
( SELECT kind, MAX(age)
FROM stuff
GROUP BY kind) maxes
WHERE
stuff.kind = maxes.kind AND
stuff.age = maxes.age
似乎真的应该有一种无需加入即可获取此信息的方法.我只需要 SQL 引擎在计算最大值时记住其他列.
It really seems like there should be a way to get this information without needing to join. I just need the SQL engine to remember the other columns when it's calculating the max.
推荐答案
无法获取 MAX 找到的行的 id,因为最长年龄的 id 可能不止一个.
You can't get the Id of the row that MAX found, because there might not be only one id with the maximum age.
这篇关于我可以将非聚合列与 group by 一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以将非聚合列与 group by 一起使用吗?
基础教程推荐
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 无法解决整理冲突 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
