mysql----group by having 配合union all 进行分组查询

1、建表模拟数据

create table t_001(
    'id' BIGINT(20) not null AUTO_INCREMENT COMMENT '主键',
    'custNo' VARCHAR(32)  COMMENT '业务编号',
    'userId' VARCHAR(32) COMMENT '用户编号',
    'createTime' TIMESTAMP  COMMENT '用户编号',
    'name' VARCHAR(32) COMMENT '名称'
)ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT '流水表';
insert into t_001 (custNo,userId,createTime,name)
values('100','1','2020-03-09 15:12:33','admin'),
('100','1','2020-03-12 15:12:33','admin'),
('200','1','2020-03-06 15:12:33','admin'),
('100','2','2020-03-01 15:12:33','abc');


SELECT * from (

(SELECT * from t_001 where custNo in(select custNo from t_001 where userID='1'  group by custNo HAVING count(custNo)>1)  
ORDER BY createTime desc LIMIT 1)
UNION all 
(SELECT * from t_001 where custNo in(    select custNo from t_001 where userID='1'  group by custNo HAVING count(custNo)=1)  )

) t ORDER BY  t.createTime desc ;

源数据

mysql----group by having 配合union all 进行分组查询_第1张图片

筛选后数据

mysql----group by having 配合union all 进行分组查询_第2张图片

你可能感兴趣的:(mysql)