7

I'll start with a simplified example of my table:

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

I'm trying to select those people who also teach the same classes as Dave. (In this case, Alice). I'm thinking of using a cursor to go through Dave's courses and selecting those people who teach the same course and intersecting the results, but I'd like to know if there is a better (simpler) way.

1
  • 1
    Self join should work. quick and easy. Commented Jan 10, 2018 at 2:42

3 Answers 3

2

Here is one method:

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');
Sign up to request clarification or add additional context in comments.

2 Comments

this has a lot of aggregations?
@VamsiPrabhala . . . "Dave" teaches all the classes that Dave teaches: "I'm trying to select those people who also teach the same classes as Dave". The OP, of course, can filter out Dave if s/he so chooses.
0

You need to use Self join, something like this

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 

Comments

0

One method, used CTE here.

;WITH CTE_Parent
AS  (
    SELECT  Name,Teaches,COUNT(*) OVER() AS Parent_Count
    FROM    @Teachers
    WHERE   Name    =   'Dave'
)

SELECT  T.Name
FROM    @Teachers   AS  T
    INNER JOIN  CTE_Parent  AS  C   ON  C.Name  <>  T.Name
                                    AND C.Teaches=  T.Teaches
GROUP BY T.Name,C.Parent_Count
HAVING  COUNT(*)    =   C.Parent_Count

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.