sql连接和获取行

时间:2018-10-01 19:18:23

标签: sql sql-server

id      dept         Person       Rating
1       ece            p1           R1  
2       ece            p2           M2     
3       eee            P6           R2             
4       eee            p2           R2
5       Civil          P7           R1
6       Civil          P3           R1
7       Civil          P8           M2
8       Mech           p7           R3
9       Mech           P3           R3

我需要在特定部门中等级为M2且其同事等级为R1的所有ID。注意:每个部门都有不同的等级。

**Output**: id
        2
        7

3 个答案:

答案 0 :(得分:4)

select id
from myTable t1
where Rating = 'M2'
and exists (select * from myTable t2 
  where t1.dept = t2.dept and t2.Rating='R1');

SQLFiddle Demo

答案 1 :(得分:0)

您可以尝试以下查询:

SELECT  DISTINCT t1.id
FROM myTable t1 LEFT JOIN
        myTable t2 ON t1.dept = t2.dept
WHERE t1.Rating = 'M2' AND t2.Rating = 'R1';

答案 2 :(得分:0)

SELECT  DISTINCT
        a.id
FROM    (
            SELECT  * FROM YourTable WHERE Rating = 'M2'
        )a
        JOIN YourTable b
            ON a.Dept = b.Dept
WHERE   b.Rating = 'R1'