By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
CREATE TABLE t
(`id` int, `season_id` int, `market` varchar(2), `result` int, `elements` int)
;
INSERT INTO t
(`id`, `season_id`, `market`, `result`, `elements`)
VALUES
(1, 20, 'fh', 75, 20),
(2, 20, 'fh', 75, 22),
(3, 20, 'SH', 81, 18),
(4, 20, 'SH', 75, 20),
(5, 21, 'fh', 90, 14),
(6, 21, 'fh', 86, 16),
(7, 21, 'SH', 90, 18),
(8, 21, 'SH', 91, 2)
;
select t.*
from (select t.*,
row_number() over (partition by season_id, market order by result desc, elements desc) as seqnum
from t
where elements > 9
) t
where seqnum = 1;
id | season_id | market | result | elements | seqnum |
---|---|---|---|---|---|
2 | 20 | fh | 75 | 22 | 1 |
3 | 20 | SH | 81 | 18 | 1 |
5 | 21 | fh | 90 | 14 | 1 |
7 | 21 | SH | 90 | 18 | 1 |
select t.*
from t
where t.id = (select t2.id
from t t2
where t2.season_id = t.season_id and t2.market = t.market and
t2.elements > 9
order by t2.result desc, t2.elements desc
limit 1
)
id | season_id | market | result | elements |
---|---|---|---|---|
2 | 20 | fh | 75 | 22 |
3 | 20 | SH | 81 | 18 |
5 | 21 | fh | 90 | 14 |
7 | 21 | SH | 90 | 18 |