I have a table of people (CarOwners
) and the types of cars they own
+-------+-------+
| Name | Model |
+-------+-------+
| Bob | Camry |
| Bob | Civic |
| Bob | Prius |
| Kevin | Civic |
| Kevin | Focus |
| Mark | Civic |
| Lisa | Focus |
| Lisa | Civic |
+-------+-------+
Given a name, how do i find other people with the exact same cars? For example, if i'm targeting Mark, no one else has ONLY a Civic so the query would return nothing. If i'm targeting Lisa, the query would return
+-------+-------+
| Name | Model |
+-------+-------+
| Kevin | Civic |
| Kevin | Focus |
+-------+-------+
Because Kevin has the exact same cars as Lisa. If i targeted Kevin, the query would return Lisa.
I created a cte which contains my target persons cars, but i'm not sure how to implement the "exact match" requirement. All of my attempts return results with subset matches.
with LisaCars as (
SELECT Model FROM CarOwners WHERE Name = 'Lisa'
)
SELECT Name, Model
FROM CarOwners
WHERE Model in (SELECT * FROM LisaCars) AND Name != 'Lisa'
This query would return all people who have either a Civic or a Focus, which isn't what i'm looking for.
+-------+-------+
| Name | Model |
+-------+-------+
| Bob | Civic |
| Kevin | Civic |
| Kevin | Focus |
| Mark | Civic |
+-------+-------+
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…