34,837
社区成员




create table tb(zcm int,yhm varchar(10), dz varchar(10))
insert into tb select 1,'a','x'
insert into tb select 2,'a','x'
insert into tb select 3,'b','y'
insert into tb select 4,'b','y'
insert into tb select 5,'b','z'
select A.zcm,A.yhm,A.dz,B.num from tb A,
(
select dz,count(dz) num,min(zcm) zcm from tb
group by dz
) B
where A.dz = B.dz and A.zcm = B.zcm
/*
zcm yhm dz num
--------------------------
1 a x 2
3 b y 2
5 b z 1
*/
drop table tb
if object_id('tempdb.dbo.#t') is not null drop table #t
create table #t(zcm int,yhm char,dz char)
insert into #t select 1,'a','x'
union all select 2,'a','x'
union all select 3,'b','y'
union all select 4,'b','y'
union all select 5,'c','z'
union all select 6,'c','y'--add
union all select 7,'c','y'--add
select zcm,t.yhm,t.dz,bs from #t t
inner join (select yhm,dz,count(1) as bs from #t group by yhm,dz) z
on t.yhm=z.yhm and t.dz=z.dz
where 1>(select count(1) from #t where dz=t.dz and yhm=t.yhm and zcm<t.zcm)
/*
zcm yhm dz bs
1 a x 2
3 b y 2
5 c z 1
6 c y 2----add
*/