CREATE TABLE A (
id int,
city varchar(255),
name varchar(255),
date_updated datetime
);
insert into A SELECT 1,'kerava', 'aaaa', '2020-12-12';
insert into A SELECT 2, 'helsinki', 'aaaa', '2021-12-12';
insert into A SELECT 3, 'vantaa', 'jjjjj', '2021-12-11';
insert into A SELECT 4, 'helsinki', 'sdsdsd', '2017-01-01';
insert into A SELECT 5, 'helsinki', 'jkkjkj', '2018-01-01';
insert into A SELECT 6, 'vantaa', 'kjjs', '2021-12-10';
SELECT * FROM A;
/*
id city name date_updated
"1" "kerava" "aaaa" "2020-12-12 00:00:00"
"2" "helsinki" "aaaa" "2021-12-12 00:00:00"
"3" "vantaa" "jjjjj" "2021-12-11 00:00:00"
"4" "helsinki" "sdsdsd" "2017-01-01 00:00:00"
"5" "helsinki" "jkkjkj" "2018-01-01 00:00:00"
"6" "vantaa" "kjjs" "2021-12-10 00:00:00"
*/
SELECT
A.city,
A.name,
A.date_updated
FROM
(
SELECT city, max(date_updated) AS max_updated
FROM A
GROUP BY city
) SORTER,
A
WHERE
A.city = SORTER.city
ORDER BY
SORTER.max_updated DESC,
A.city ASC,
A.date_updated DESC
;
/*
city name date_updated
"helsinki" "aaaa" "2021-12-12 00:00:00"
"helsinki" "jkkjkj" "2018-01-01 00:00:00"
"helsinki" "sdsdsd" "2017-01-01 00:00:00"
"vantaa" "jjjjj" "2021-12-11 00:00:00"
"vantaa" "kjjs" "2021-12-10 00:00:00"
"kerava" "aaaa" "2020-12-12 00:00:00"
*/
SELECT
A.city,
A.name,
A.date_updated
FROM
(
SELECT city, max(date_updated) AS max_updated
FROM A
GROUP BY city
) SORTER JOIN A ON (
A.city = SORTER.city
)
ORDER BY
SORTER.max_updated DESC,
A.city ASC,
A.date_updated DESC
;
-- sama tulos kuin edellisellä