根据某个字段去重 根据另一个字段排序的一个SQL

时间:2021-09-19 15:05:25

背景:
一张表 有 name , crt_time , work_sts 三个字段

这张表里存在这样的数据

'a', '2018-12-18 21:37:24', '未'
'a', '2018-12-19 09:37:24', '完'
'a', '2018-12-19 21:37:24', '未'
'b', '2018-11-18 21:37:24', '完'
'b', '2018-11-19 20:37:24', '完'
'b', '2018-11-20 09:37:24', '完'
'c', '2018-11-18 21:47:24', '完'
'c', '2018-11-19 20:57:24', '完'
'c', '2018-11-20 09:33:24', '未'
'd', '2018-12-18 21:17:24', '未'
'd', '2018-12-19 09:17:24', '完'
'd', '2018-12-19 21:17:24', '完'

现在需要根据 name 去重 要求如下:
1. 同一个name下 work_sts没有 未 的时候 取 完 数据里 crt_time 最大的那条数据
2. 同一个name下 work_sts有一个 未 取 未 这条数据
3. 同一个name下 work_sts有多个 未 取 未 数据里 crt_time 最大的那条数据

 

答案:

 

SELECT a.*
FROM t_test a
JOIN(
SELECT col1,MAX(col2) col2
FROM t_test
WHERE col3=''
GROUP BY col1
HAVING SUM(IF(col3='',1,0)) > 0
)b
WHERE a.col1 = b.col1 AND a.col2 = b.col2
UNION
SELECT a.*
FROM t_test a
JOIN (
SELECT col1,MAX(col2) col2
FROM t_test
GROUP BY col1
HAVING SUM(IF(col3='',1,0)) = 0
)c
WHERE a.col1 = c.col1 AND a.col2 = c.col2
ORDER BY col1
CREATE TABLE `t_test` (
  `col1` varchar(32) DEFAULT NULL COMMENT 'col1',
  `col2` varchar(128) DEFAULT NULL COMMENT 'col2',
  `col3` varchar(64) DEFAULT NULL COMMENT 'col3',
  `id` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8


INSERT INTO `t_test` (`col1`, `col2`, `col3`, `id`) VALUES ('a', '2018-12-18 21:37:24', '', '100');
INSERT INTO `t_test` (`col1`, `col2`, `col3`, `id`) VALUES ('a', '2018-12-19 09:37:24', '', '100');
INSERT INTO `t_test` (`col1`, `col2`, `col3`, `id`) VALUES ('a', '2018-12-19 21:37:24', '', '100');
INSERT INTO `t_test` (`col1`, `col2`, `col3`, `id`) VALUES ('b', '2018-11-18 21:37:24', '', '100');
INSERT INTO `t_test` (`col1`, `col2`, `col3`, `id`) VALUES ('b', '2018-11-19 20:37:24', '', '100');
INSERT INTO `t_test` (`col1`, `col2`, `col3`, `id`) VALUES ('b', '2018-11-20 09:37:24', '', '100');
INSERT INTO `t_test` (`col1`, `col2`, `col3`, `id`) VALUES ('c', '2018-11-18 21:47:24', '', '100');
INSERT INTO `t_test` (`col1`, `col2`, `col3`, `id`) VALUES ('c', '2018-11-19 20:57:24', '', '100');
INSERT INTO `t_test` (`col1`, `col2`, `col3`, `id`) VALUES ('c', '2018-11-20 09:33:24', '', '100');
INSERT INTO `t_test` (`col1`, `col2`, `col3`, `id`) VALUES ('d', '2018-12-18 21:17:24', '', '100');
INSERT INTO `t_test` (`col1`, `col2`, `col3`, `id`) VALUES ('d', '2018-12-19 09:17:24', '', '100');
INSERT INTO `t_test` (`col1`, `col2`, `col3`, `id`) VALUES ('d', '2018-12-19 21:17:24', '', '100');