GROUP BY与MAX(date)
我试图列出每个列车的最新目的地(最大出发时间), 例如 :
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 BYexpression式”的错误,说我必须在我的group by语句中包含“Dest”。 但肯定不是我想要的
是否可以在一行SQL中执行?
您不能在结果集中包含未分组的非聚合列。 如果一列火车只有一个目的地,那么只需将目的地列添加到您的group by子句中,否则您需要重新考虑您的查询。
尝试:
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
SELECT train, dest, time FROM ( SELECT train, dest, time, RANK() OVER (PARTITION BY train ORDER BY time DESC) dest_rank FROM traintable ) where dest_rank = 1
下面是一个只使用左连接的例子,我认为它比任何一个组的方法都更有效率: ExchangeCore博客
SELECT t1.* FROM TrainTable t1 LEFT JOIN TrainTable t2 ON (t1.Train = t2.Train AND t1.Time < t2.Time) WHERE t2.Time IS NULL;
只要没有重复(火车一次只能到达一个车站)…
select Train, MAX(Time), max(Dest) keep (DENSE_RANK LAST ORDER BY Time) max_keep from TrainTable GROUP BY Train;
另一个scheme
select * from traintable where (train, time) in (select train, max(time) from traintable group by train);
我知道我迟到了,但试试这个…
SELECT `Train`, `Dest`, SUBSTRING_INDEX(GROUP_CONCAT(`Time` ORDER BY `Time` DESC), ",", 1) AS `Time` FROM TrainTable GROUP BY Train;
Src: 组Concat文档
编辑:固定的SQL语法