Having problem with complex order.
Here is structure and data:
CREATE TABLE `mail_test` (
`id` int(10) UNSIGNED NOT NULL,
`account_id` int(10) UNSIGNED NOT NULL,
`score` float UNSIGNED NOT NULL,
`from` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `mail_test` (`id`, `account_id`, `score`, `from`) VALUES
(1, 1, 0, '[email protected]'),
(2, 2, 0, '[email protected]'),
(3, 3, 3, '[email protected]'),
(4, 5, 4, '[email protected]'),
(5, 3, 1, '[email protected]'),
(6, 9, 0.5, '[email protected]'),
(7, 9, 3, '[email protected]'),
(8, 8, 2, '[email protected]');
Desired output:
(4, 5, 4, '[email protected]'),
(7, 9, 3, '[email protected]'),
(3, 3, 3, '[email protected]'),
(5, 3, 1, '[email protected]'),
(8, 8, 2, '[email protected]');
(6, 9, 0.5, '[email protected]'),
(1, 1, 0, '[email protected]'),
(2, 2, 0, '[email protected]'),
The order logic: first is row with greatest score (parent row), then rows (child rows) with same account_id
and from
with parent row. If no child rows – again next row with great score. So order by score DESC. But rows grouped by same account_id
and from
.
mysql version 5.7
3
Answers
This can be done using
row_number()
andmax()
:This is a working solution on mysql 5.7 :
Result :
Demo here
fiddle
This version works without partitions: