34,873
社区成员
发帖
与我相关
我的任务
分享
NAME PASS AGE DEPT
-------------------- -------------------- ---------------------- --------------------
q1 11 12 oo
q1 11 22 oo
q2 11 25 oo
q3 11 42 oo
q4 11 32 pp
q5 11 56 p
q6 11 74 p
q7 11 58 p
q8 11 63 p
q9 11 36 kk
qq 11 28 kk
q1w 11 65 kk
q1e 11 45 kk
q1r 11 36 kk
q1t 11 75 m
q1y 11 251 m
q1u 11 45 bb
q1i 11 56 bb
q1f 11 34 bb
q1g 11 63 bb
q1j 11 25 bb
q1k 11 61 bb
q1l 11 44 y
if not object_id('tb') is null
drop table tb
Go
Create table tb([NAME] nvarchar(3),[PASS] int,[AGE] int,[DEPT] nvarchar(2))
Insert tb
select N'q1',11,12,N'oo' union all
select N'q1',11,22,N'oo' union all
select N'q2',11,25,N'oo' union all
select N'q3',11,42,N'oo' union all
select N'q4',11,32,N'pp' union all
select N'q5',11,56,N'p' union all
select N'q6',11,74,N'p' union all
select N'q7',11,58,N'p' union all
select N'q8',11,63,N'p' union all
select N'q9',11,36,N'kk' union all
select N'qq',11,28,N'kk' union all
select N'q1w',11,65,N'kk' union all
select N'q1e',11,45,N'kk' union all
select N'q1r',11,36,N'kk' union all
select N'q1t',11,75,N'm' union all
select N'q1y',11,251,N'm' union all
select N'q1u',11,45,N'bb' union all
select N'q1i',11,56,N'bb' union all
select N'q1f',11,34,N'bb' union all
select N'q1g',11,63,N'bb' union all
select N'q1j',11,25,N'bb' union all
select N'q1k',11,61,N'bb' union all
select N'q1l',11,44,N'y'
Go
Select *
from tb t
where (select count(*)
from tb
where [DEPT]=t.[DEPT] and age>t.age)<1
/*
NAME PASS AGE DEPT
---- ----------- ----------- ----
q3 11 42 oo
q4 11 32 pp
q6 11 74 p
q1w 11 65 kk
q1y 11 251 m
q1g 11 63 bb
q1l 11 44 y
*/只写了一部分的测试数据
if object_id('tb') is not null
drop table tb
create table tb
(
Name nvarchar(20),
PASS int,
ACG int,
DEPT char(10)
)
insert into tb select 'q1',11,12,'oo'
union all
select 'q1',11,22,'oo'
union all
select 'q2',11,25,'oo'
union all
select 'q3',11,42,'oo'
union all
select 'q4',11,32,'pp'
union all
select 'q5',11,56,'p'
union all
select 'q6',11,74,'p'
union all
select 'q7',11,58,'p'
union all
select 'q8',11,63,'p'
select * from tb t
where not exists(select * from tb where DEPT=t.DEPT and ACG>t.ACG)
Name PASS ACG DEPT
-------------------- ----------- ----------- ----------
q3 11 42 oo
q4 11 32 pp
q6 11 74 p
(3 行受影响)
select max(age)as age, dept from tb_Age
group by dept
select NAME , PASS , AGE , DEPT
from tb t
where not exists(select 1 from tb where dept=t.dept and t.age<age)