22,181
社区成员




drop table ta
go
create table ta
([id] int,
Mc char(1),
age int
)
go
insert into ta
select 1,'A',5
union all
select 2,'A',7
union all
select 3,'A',-8
union all
select 4,'A',5
union all
select 5,'B',1
union all
select 6,'B',3
union all
select 7,'B',-5
union all
select 8,'C',4
union all
select 9,'C',3
union all
select 10,'C',3
union all
select 11,'D',10
---
select max(id) [id],mc,age from ta a where age in (select min(age) from ta b where age>=0 and a.mc=b.mc group by mc)
group by mc,age order by id
/*
id mc age
----------- ---- -----------
4 A 5
5 B 1
10 C 3
11 D 10
*/
create table ta
([id] int,
Mc char(1),
age int
)
go
insert into ta
select 1,'A',5
union all
select 2,'A',7
union all
select 3,'A',-8
union all
select 4,'B',5
union all
select 5,'B',1
union all
select 6,'B',3
union all
select 7,'B',-5
union all
select 8,'C',4
union all
select 9,'C',3
union all
select 10,'C',3
union all
select 11,'D',10
---
select max(id) [id],age from ta where age in (select min(age) from ta where age>=0 group by mc) group by age order by id
/*
id age
----------- -----------
4 5
5 1
10 3
11 10
(所影响的行数为 4 行)
*/
create table tb(id int,mc varchar(5),age int)
go
insert tb select 1 ,'A' ,5
insert tb select 2 ,'A' ,7
insert tb select 3 ,'A' ,-8
insert tb select 4 ,'A', 5
insert tb select 5 ,'B' ,1
insert tb select 6 ,'B' ,3
insert tb select 7 ,'B' ,-5
insert tb select 8 ,'C' ,4
insert tb select 9 ,'C' ,3
insert tb select 10 ,'C' ,3
insert tb select 11 ,'D' ,10
--modify
select a.* from tb a,
(select mc,min(AGE) AGE from tb where AGE>=0 group by mc) b
where a.mc=b.mc and a.age=b.age and not exists(select 1 from tb where mc=a.mc and age=a.age and id>a.id)
/*
id mc age
----------- ----- -----------
4 A 5
5 B 1
10 C 3
11 D 10
*/
select * from tb a
where not exists(select 1 from tb where mc = a.mc and id >a.id and age >a.age)
select a.* from tb a,
(select mc,min(AGE) AGE from tb where AGE>0 group by mc) b
where a.mc=b.mc and a.age=b.age and exists(select 1 from tb where mc=a.mc and age=a.age and id>a.id)