find duplicate records in related tables
-
23-02-2021 - |
Question
Consider the following data structure:
parking garages
|
|_ garage 1
|__ red car
|__ blue car
|_ garage 2
|__ yellow car
|__ orange car
|_ garage 3
|__ red car
|__ red car
|__ yellow car
"parking garages" is a table, and each entry is a foreign key to a "garageCars" table containing one record for each car in the garage.
What I would like to do is write a query that would return "garage 3" because it has 2 red cars
I've tried using the HAVING clause with a count, but this returns all the rows that have more than 1 car. I need something more along the lines of "WHERE count(car) > 1 and car.color = car.color".
Solution
Assuming you only want the garage name and not the color that's duped because you want "... query that would return "garage 3" because it has 2 red cars"
Using a Derived Table
SELECT g.garagename
FROM garage g
INNER JOIN (SELECT garage_id
FROM cars
GROUP BY garage_id,
carcolor
HAVING COUNT(garage_id) > 1) c
ON g.garage_id = c.garage_id
Using IN
SELECT g.garagename
FROM garage g
WHERE g.garage_id IN (SELECT garage_id
FROM cars
GROUP BY garage_id,
carcolor
HAVING COUNT(garage_id) > 1)
You could also do it with EXISTS, CROSS APPLY or with a CTE
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow