GROUP BY with MAX(DATE)(GROUP BY with MAX(DATE))
问题描述
我正在尝试在表格中列出每列火车的最新目的地(最长出发时间),例如:
I'm trying to list the latest destination (MAX departure time) for each train in a table, for example:
Train Dest Time
1 HK 10:00
1 SH 12:00
1 SZ 14:00
2 HK 13:00
2 SH 09:00
2 SZ 07:00
期望的结果应该是:
Train Dest Time
1 SZ 14:00
2 HK 13:00
我尝试过使用
SELECT Train, Dest, MAX(Time)
FROM TrainTable
GROUP BY Train
我收到ora-00979 不是 GROUP BY 表达式"错误,提示我必须在 group by 语句中包含Dest".但这肯定不是我想要的……
by I got a "ora-00979 not a GROUP BY expression" error saying that I must include 'Dest' in my group by statement. But surely that's not what I want...
是否可以在一行 SQL 中完成?
Is it possible to do it in one line of SQL?
推荐答案
您不能在结果集中包含未分组的非聚合列.如果一列火车只有一个目的地,那么只需将目的地列添加到您的 group by 子句中,否则您需要重新考虑您的查询.
You cannot include non-aggregated columns in your result set which are not grouped. If a train has only one destination, then just add the destination column to your group by clause, otherwise you need to rethink your query.
试试:
SELECT t.Train, t.Dest, r.MaxTime
FROM (
SELECT Train, MAX(Time) as MaxTime
FROM TrainTable
GROUP BY Train
) r
INNER JOIN TrainTable t
ON t.Train = r.Train AND t.Time = r.MaxTime
这篇关于GROUP BY with MAX(DATE)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:GROUP BY with MAX(DATE)


基础教程推荐
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 带更新的 sqlite CTE 2022-01-01