22,209
社区成员
发帖
与我相关
我的任务
分享
--应该是这个吧?
a 1
b 1
c 1
d 1
g 8
b 8
c 8
--查询
select distinct b.b,a.b
from TableTmp a,TableTmp b
where a.b<>b.b
and a.a=b.a
and (select count(1) from TableTmp where b=a.b)>(select count(1) from TableTmp where b=b.b)
and (select count(1) from TableTmp c where b=b.b and a<>b.a and not exists (
select 1 from TableTmp where a=c.a and b=a.b)
)=0
CREATE TABLE TableTmp(
[a] [varchar] (50),
[b] [varchar] (50)
)
GO
insert into TableTmp(a,b) values('a','1');
insert into TableTmp(a,b) values('b','1');
insert into TableTmp(a,b) values('c','1');
insert into TableTmp(a,b) values('d','1');
insert into TableTmp(a,b) values('a','5');
insert into TableTmp(a,b) values('b','5')
insert into TableTmp(a,b) values('a','6')
insert into TableTmp(a,b) values('b','6')
insert into TableTmp(a,b) values('g','7')
insert into TableTmp(a,b) values('b','7')
insert into TableTmp(a,b) values('g','8')
insert into TableTmp(a,b) values('b','8')
insert into TableTmp(a,b) values('c','8')
go
--查询
select distinct a.b,b.b
from TableTmp a,TableTmp b
where a.b<>b.b
and a.a=b.a
and (select count(1) from TableTmp where b=a.b)>(select count(1) from TableTmp where b=b.b)
and (select count(1) from TableTmp c where b=b.b and a<>b.a and not exists (
select 1 from TableTmp where a=c.a and b=a.b)
)=0
--结果
b b
-------------------------------------------------- --------------------------------------------------
1 5
1 6
8 7
(所影响的行数为 3 行)
set nocount on
CREATE TABLE TableTmp(
[a] [varchar] (50),
[b] [varchar] (50)
)
GO
insert into TableTmp(a,b) values('a','1');
insert into TableTmp(a,b) values('b','1');
insert into TableTmp(a,b) values('c','1');
insert into TableTmp(a,b) values('d','1');
insert into TableTmp(a,b) values('a','5');
insert into TableTmp(a,b) values('b','5')
insert into TableTmp(a,b) values('a','6')
insert into TableTmp(a,b) values('b','6')
insert into TableTmp(a,b) values('g','7')
insert into TableTmp(a,b) values('b','7')
insert into TableTmp(a,b) values('g','8')
insert into TableTmp(a,b) values('b','8')
insert into TableTmp(a,b) values('c','8')
go
select * from tabletmp
where b =
(select top 1 b
from tabletmp
group by b
order by count(1) desc )
drop table tabletmp
/*
a b
-------------------------------------------------- --------------------------------------------------
a 1
b 1
c 1
d 1
*/