【问题标题】:Select duplicate values选择重复值
【发布时间】:2019-04-02 09:38:47
【问题描述】:
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 的重复值(如果有的话),然后只选择具有“室友”或“英语老师”关系的那些。

我的期望值:

   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(*) 的查询,但这并不能解决问题。我不想要重复的计数,我希望将重复分组在一起。

【问题讨论】:

  • 您使用的是哪个DBMS 产品? “SQL”只是一种查询语言,而不是特定数据库产品的名称。请为您正在使用的数据库产品添加tag postgresql, oracle, sql-server, db2, ...

标签: sql-server join select duplicates


【解决方案1】:

这不是你想要的输出,但它包含相同的信息:

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;

【讨论】:

    【解决方案2】:

    试试这个:

        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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-11
      • 2016-08-06
      • 2016-06-30
      • 2014-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多