SQL - 如何选择具有相同多个值的行

时间:2018-01-10 02:39:51

标签: sql sql-server select

我将从我的表格的简化示例开始:

+-----+----------+
|Name |Teaches   |
+-----+----------+  
|Dave |Science   |
+-----+----------+  
|Dave |History   |
+-----+----------+  
|Alice|History   |
+-----+----------+  
|Alice|Literature|
+-----+----------+  
|Alice|Science   |
+-----+----------+  
|John |History   |
+-----+----------+

我试图选择那些和Dave一样教授同一课程的人。 (在这种情况下,爱丽丝)。我想用光标浏览Dave的课程,选择那些教授相同课程并交叉结果的人,但我想知道是否有更好的(更简单的)方式。

3 个答案:

答案 0 :(得分:2)

这是一种方法:

select t.name
from t join
     t td
     on td.teaches = t.teaches 
where td.name = 'Dave'
group by t.name
having count(*) = (select count(*) from t where t.name = 'Dave');

答案 1 :(得分:0)

您需要使用Self join,类似这样的

SELECT a.NAME
FROM   Table1 a
       INNER JOIN (SELECT Teaches,
                          Count(*)OVER() AS cnt
                   FROM   Table1
                   WHERE  NAME = 'Dave') b
               ON a.Teaches = b.Teaches
WHERE  a.NAME <> 'Dave'
GROUP  BY a.NAME,
          b.cnt
HAVING Count(*) = b.cnt 

答案 2 :(得分:0)

一种方法,在这里使用class Box<T> { var contents: T init(_ contents: T) { self.contents = contents } } class ClassA { var arrInt = Box([1,2,3]) } class ClassB { let arrInt: Box<[Int]> init(_ arrInt: Box<[Int]>) { self.arrInt = arrInt } } let objectA = ClassA() let objectB = ClassB(objectA.arrInt) objectA.arrInt.contents.append(4) print(objectB.arrInt.contents)

CTE