MySQL组通过选择最完整的记录

时间:2016-07-27 13:42:07

标签: mysql

我有一个像这样的记录列表:

id    state   description   date
3340  KO      test          2016-07-27
3340  KO                    2016-07-27
3340  AQ      blalba        2016-07-27
3340  AC                    2016-07-27

我需要按州分组,选择重复状态记录之间最完整的记录,如下面的结果:

id    state   description   date
3340  KO      test          2016-07-27
3340  AQ      blalba        2016-07-27
3340  AC                    2016-07-27

1 个答案:

答案 0 :(得分:0)

这项工作可以帮助您获得预期的结果:

SET @row_number = 0;

SELECT id, `state`, `description`, `date`
FROM (
    SELECT *, (@row_number:=@row_number + 1) AS num
    FROM TestTable
    ORDER BY IF (`description` <> '', 0, 1)
    ) T
GROUP BY id, `state`

Working DEMO

使用给定数据执行示例:

CREATE TABLE TestTable(id INT, `state` VARCHAR(2), `description` VARCHAR(100), `date` DATE);

INSERT INTO TestTable (id, `state`, `description`, `date`) VALUES
(3340, 'KO', ''       , '2016-07-27'),
(3340, 'KO', 'test'   , '2016-07-27'),
(3340, 'AQ', 'blalba' , '2016-07-27'),
(3340, 'AC', ''       , '2016-07-27');

SET @row_number = 0;

SELECT id, `state`, `description`, `date`
FROM (
    SELECT *, (@row_number:=@row_number + 1) AS num
    FROM TestTable
    ORDER BY IF (`description` <> '', 0, 1)
    ) T
GROUP BY id, `state`