选择重复的值

时间:2018-10-29 12:44:15

标签: sql-server join select duplicates

table1  dorm_ID   Person_ID
          145       66689
          146       66692
          150       66585
          151       68989

table2    P1      P2    Relationship
         78989  66689      Roommate
         58596  66689      Bio teacher
         79858  66689      English teacher
         88859  66692      Roommate
         58597  66692      English teacher
         98557  66585      Roommate
         98999  68989      Chemistry teacher
         98992  68989      English teacher

我想选择同时具有室友和英语老师的dorm_ID。我需要在Person_ID = P2上加入表。有没有一种方法可以设置查询,该查询选择dorm_id的重复值(如果有),然后仅选择具有“ Roomate”或“英语老师”关系的值。

我的期望值:

   dorm_ID   Person_ID     P1     P2      Relationship
     145       66689      78989  66689      Roommate
     145       66689      79858  66689      English teacher
     146       66692      88859  66692      Roommate
     146       66692      58597  66692      English teacher

我尝试使用涉及HAVING COUNT(*)的查询,但这不能解决问题。我不希望重复项的数量,我希望重复项组合在一起。

2 个答案:

答案 0 :(得分:0)

这不完全是您想要的输出,但是包含相同的信息:

select t1.dorm_id, t1.person_id,
       group_concat(distinct t2.p1),
       group_concat(distinct t2.p2)
from table2 t2 join
     table1 t1
     on t2.p1 = t1.person_id 
group by t1.dorm_id, t1.person_id
having sum(case when t2.relationship = 'Roommate' then 1 else 0 end) > 0 and
       sum(case when t2.relationship = 'English teacher' then 1 else 0 end) > 0;

答案 1 :(得分:0)

尝试一下:

    Select 
  a.dorm_id, 
  a.person_id, 
  b.p1, 
  b.p2, 
  b.relationship 
FROM table1 a 
  JOIN (
    Select 
      p1, 
      p2, 
      relationship 
    FROM 
      (
        Select p2 
        FROM table2 
        WHERE relationship in ('Roommate', 'English teacher') 
        GROUP BY p2 
        HAVING count(*) > 1
      ) b 
      JOIN table2 c ON c.p2 = b.p2 
    WHERE c.relationship in ('Roommate', 'English teacher')
  ) d ON a.Person_ID = d.P2;