[英]SQL Server 2014 duplicates
您可以使用子查詢來獲取屬於group = 100的機構的名稱,然后使用in
從institution
in
獲取行:
select * from institution
where name in (
select i.name
from institution i inner join department d
on d.departmentid = i.departmentid
inner join group g
on g.groupid = d.groupid
where g.groupid = 100
)
使用前兩個表的institution
和department
就足夠了, in
operator和exists
子句中使用:
select *
from institution
where institutionname in
(
select i.institutionname
from institution i
where exists ( select 1 from department d where groupid = 100 )
group by i.institutionname
having count(i.institutionname)>1
);
institutionid institutionname deparmentid
1 ABC 123
2 ABC 456
編輯: 我想你想要更多(通過使用“組”表):
with institution( institutionid, institutionname, deparmentid, city ) as
(
select 1,'ABC',123,'New York' union all
select 2,'ABC',456,'New York' union all
select 3,'DEF',123,'Chicago' union all
select 4,'GHI',789,'Los Angeles'
),
department( deparmentid, deparmentname, groupid ) as
(
select 123,'dept1',100 union all
select 456,'dept2',101 union all
select 789,'dept3',102
),
"group"( groupid, groupname ) as
(
select 100,'Group A'
)
select ii.*, g.groupname, dd.deparmentname
from institution ii
left join department dd on dd.deparmentid = ii.deparmentid
left join "group" g on g.groupid = dd.groupid
where ii.institutionname in
(
select i.institutionname
from institution i
where exists ( select 1 from department d where d.groupid = 100 )
group by i.institutionname
having count(i.institutionname)>1 and count(i.city)>1
);
institutionid institutionname deparmentid city groupname deparmentname
1 ABC 123 New York Group A dept1
2 ABC 456 New York NULL dept2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.