自关联与not exists,查询出最大年段的客户信息

所用数据库mysql5.7

1、创建表:create table query1(id int not null auto_increment,custId varchar(6),startYear varchar(6),primary key(id))

 

 

 2、插入数据:

INSERT into query1 (custId,startYear) VALUES 
('1','1990'),
('1','1991'),
('1','1992'),
('1','2000'),
('1','2002'),
('1','2002'),
('2','1990'),
('3','1990'),
('3','1990'),
('4','1990'),
('4','1991'),
('4','1992'),
('4','2000'),
('4','2008'),
('4','2008'),
('5','1990'),
('5','1991'),
('5','2000'),
('5','2000'),
('5','2008'),
('5','2008')

3、sql:

select distinct q1.custId,q1.startYear from query1 q1 WHERE
not exists (select '1' from query1 q2 WHERE q1.custId=q2.custId and q1.startYear<q2.startYear)

查看结果:

 

 由于同一个custId可以存着重复的年段,所以用distinct去重

posted @ 2019-09-14 16:59  雷雨客  阅读(344)  评论(0编辑  收藏  举报