Mysql GROUP BY ...但我想要最旧的

Mysql GROUP BY ...but I want the oldest one

我想按类别对我的结果进行分组,但该组中的用户年龄最大,但我无法决定是哪一个...

|NAME  |DATE      |CATEGORY |ID
|bill  |2021-12-24|NULL     |6
|adrian|2021-12-23|NULL     |4
|steeve|2021-12-20|20       |8
|jak   |2021-12-14|NULL     |5
|peter |2021-12-01|10       |3
|rick  |2014-10-23|10       |2
|jean  |2012-12-12|10       |1
|bob   |2000-12-26|20       |7
|arnold|1950-12-10|20       |9

这是我重现问题的请求,实际上它要复杂得多,但足以说明问题

SELECT * FROM my_table GROUP BY ifnull(category,id) ORDER BY date DESC 

得到的结果不是我想要的,因为分组出来的用户不是最老的

|NAME  |DATE      |CATEGORY |ID
|bill  |2021-12-24|NULL     |6
|adrian|2021-12-23|NULL     |4
|jak   |2021-12-14|NULL     |5
|jean  |2012-12-12|10       |1
|bob   |2000-12-26|20       |7

对于类别 20,我希望得到 arnold 而不是 bob

这里是 Mysql 的真实数据集,如果它可以帮助解决这个黑暗的故事

CREATE TABLE `my_table` (
  `name` varchar(20) CHARACTER SET utf8mb3 NOT NULL,
  `date` date NOT NULL,
  `category` int(20) DEFAULT NULL,
  `id` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `test` (`name`, `date`, `category`, `id`) VALUES
('jean', '2012-12-12', 10, 1),
('rick', '2014-10-23', 10, 2),
('peter', '2021-12-01', 10, 3),
('adrian', '2021-12-23', NULL, 4),
('jak', '2021-12-14', NULL, 5),
('bill', '2021-12-24', NULL, 6),
('bob', '2000-12-26', 20, 7),
('steeve', '2021-12-20', 20, 8),
('arnold', '1950-12-10', 20, 9);

使用ROW_NUMBER我们可以尝试:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY COALESCE(category, id)
                                 ORDER BY date DESC) rn
    FROM test
)

SELECT name, date, category, id
FROM cte
WHERE rn = 1;