I have a table called residents that includes information about residents living in different apartment complexes. This is what selecting all values from this table would look like -
SELECT * FROM RESIDENTS;
aptid | aptnum | ssn
---------+-----------------+----------------
100 | 1 | 641072301
100 | 2 | 699021306
100 | 3 | 699021306
100 | 1 | 699021306
200 | 1 | 132429609
200 | 1 | 641072301
300 | 1 | 641072301
I want to select the social security numbers of all of the residents who are renting out more than three apartment in DIFFERENT complexes. So for example, resident with the ssn '641072301' will show up in the query because this person is renting out at least three units in complex ID 100, 200, 300 , where as the person with the social of '699021306' will not show up, because, even though they are renting out three different apartments, they are all within the same unit (aptID). so the result in this case would be -
ssn
---------+
641072301
(1 row)
This is what I have, but it is no giving me what I want -
SELECT r1.ssn
FROM Residents r1
, Residents r2
WHERE r1.aptID <> r2.apt.ID;
Try this:
SELECT ssn
FROM Residents
GROUP BY ssn
HAVING COUNT(DISTINCT aptid) >= 3