有表如下
列1 列2 列3
A 张 1
A 张 2
A 王 3
A 王 4
B 张 1
B 张 3
B 王 4查询此表
条件是列2 = 王且列3 是 按列1分组后每个分组中的最大值上表结果应该是列1 列2 列3
A 王 4
B 王 4
列1 列2 列3
A 张 1
A 张 2
A 王 3
A 王 4
B 张 1
B 张 3
B 王 4查询此表
条件是列2 = 王且列3 是 按列1分组后每个分组中的最大值上表结果应该是列1 列2 列3
A 王 4
B 王 4
insert into @t select 'A' , '张' ,1 union all
select 'A' , '张' , 2 union all
select 'A' , '王' , 3 union all
select 'A' , '王' , 4 union all
select 'B' , '张' , 1 union all
select 'B' , '张' , 3 union all
select 'B' , '王' , 4select 列1,列2,max(列3) as 列3 from @t where 列2='王' group by 列1,列2
where 列2='王'
and not exists(
select * from tb
where 列2='王'
and 列1=a.列1 and 列3>a.列3)
insert into #t (列1, 列2 , 列3)
select 'A','张',1 union all
select 'A','张',2 union all
select 'A','王',3 union all
select 'A','王',4 union all
select 'B','张',1 union all
select 'B','张',3 union all
select 'B','王',4select * from #tselect 列1,min(列2) as 列2,max(列3) as 列3
from #t
where 列2 = '王'
group by 列1
order by 列1drop table #t
/*
列1 列2 列3
A 王 4
B 王 4
*/
insert into #t (列1, 列2 , 列3)
select 'A','张',1 union all
select 'A','张',2 union all
select 'A','王',3 union all
select 'A','王',4 union all
select 'B','张',1 union all
select 'B','张',3 union all
select 'B','王',4select *
from #t
where 列2='王' and 列3 in (select max(列3) from #t where 列2='王')
insert into #t (列1, 列2 , 列3)
select 'A','张',1 union all
select 'A','张',2 union all
select 'A','王',3 union all
select 'A','王',4 union all
select 'B','张',1 union all
select 'B','张',3 union all
select 'B','王',4
select * from #t T where T.列3=(select top 1 列3 from #t where 列1=T.列1 order by 列3 DESC)
A 张 1
A 张 2
A 王 3
A 王 4
B 张 1
B 张 3
B 王 4
C 王 3
C 张 4
D 张 3
D 张 5
上表我想得到
列1 列2 列3
A 王 4
B 王 4也就是说,我先想找出A、B、C、D中列3最大的一行,然后想在这个集合中再筛选出列2为‘王’的行
select* from 表 where 列2='王' and 列3
in (select max(列3) from 表 group by 列1)
where not exists(select * from tb where 列1=a.列1 and 列3>a.列3)
and 列2='王'