Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
sql连接和获取行_Sql_Sql Server - Fatal编程技术网

sql连接和获取行

sql连接和获取行,sql,sql-server,Sql,Sql Server,我需要所有Id的评级是M2和他们的同事评级是R1在一个特定的部门注意:每个部门可能有不同的评级 id dept Person Rating 1 ece p1 R1 2 ece p2 M2 3 eee P6 R2 4 eee p

我需要所有Id的评级是M2和他们的同事评级是R1在一个特定的部门注意:每个部门可能有不同的评级

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

您可以尝试以下查询:

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

这是迄今为止最有效的解决方法!
select id
from myTable t1
where Rating = 'M2'
and exists (select * from myTable t2 
  where t1.dept = t2.dept and t2.Rating='R1');
SELECT  DISTINCT t1.id
FROM myTable t1 LEFT JOIN
        myTable t2 ON t1.dept = t2.dept
WHERE t1.Rating = 'M2' AND t2.Rating = 'R1';
SELECT  DISTINCT
        a.id
FROM    (
            SELECT  * FROM YourTable WHERE Rating = 'M2'
        )a
        JOIN YourTable b
            ON a.Dept = b.Dept
WHERE   b.Rating = 'R1'