SQl group by to get the defaults

时间:2018-04-18 17:48:26

标签: sql oracle

I have two tables person and address. Person can have multiple address . Address table has a is_default flag on it. For each person one address has to be selected as is_default , I need to pull up a list of person of which it does not have is_default flag set . Only one address can be set as default.

Below is the query I wrote which is not pulling the right data.

SELECT * FROM Person p WHERE p.pid IN (select a.pid from Address a
where a.is_default <> -1 group by a.pid)

1 个答案:

答案 0 :(得分:3)

You could use NOT EXISTS and correlated subquery:

SELECT *
FROM Person p
WHERE NOT EXISTS(SELECT * FROM Address a 
                 WHERE a.is_default = 1 AND p.pid = a.pid)