GROUP BY with MAX(DATE)

时间:2010-08-16 07:30:56

标签: sql oracle group-by greatest-n-per-group ora-00979

我正在尝试列出表格中每列火车的最新目的地(最长出发时间),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'。但肯定不是我想要的......

是否可以在一行SQL中执行此操作?

6 个答案:

答案 0 :(得分:146)

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

答案 1 :(得分:136)

您不能在结果集中包含未分组的非聚合列。如果列车只有一个目的地,那么只需将目标列添加到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

答案 2 :(得分:72)

这是一个仅使用左连接的示例,我相信通过方法比任何组更有效:ExchangeCore Blog

SELECT t1.*
FROM TrainTable t1 LEFT JOIN TrainTable t2
ON (t1.Train = t2.Train AND t1.Time < t2.Time)
WHERE t2.Time IS NULL;

答案 3 :(得分:11)

另一种解决方案:

select * from traintable
where (train, time) in (select train, max(time) from traintable group by train);

答案 4 :(得分:8)

只要没有重复(火车往往只能一次到达一个车站)......

select Train, MAX(Time),
      max(Dest) keep (DENSE_RANK LAST ORDER BY Time) max_keep
from TrainTable
GROUP BY Train;

答案 5 :(得分:4)

我知道我迟到了,但试试这个......

SELECT 
    `Train`, 
    `Dest`,
    SUBSTRING_INDEX(GROUP_CONCAT(`Time` ORDER BY `Time` DESC), ",", 1) AS `Time`
FROM TrainTable
GROUP BY Train;

Src:Group Concat Documentation

编辑:修复sql语法