This question already has an answer here:
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
The desired result should be:
Train Dest Time
1 SZ 14:00
2 HK 13:00
I have tried using
SELECT Train, Dest, MAX(Time)
FROM TrainTable
GROUP BY Train
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...
Is it possible to do it in one line of SQL?
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.
Try:
As long as there are no duplicates (and trains tend to only arrive at one station at a time)...
I know I'm late to the party, but try this...
Src: Group Concat Documentation
Edit: fixed sql syntax
Another solution:
Here's an example that only uses a Left join and I believe is more efficient than any group by method out there: ExchangeCore Blog