Reputation: 59
I'm racking my brain trying to work out what group by and/or distinct and count()
formation help with this but have currently drawn a blank.
Consider the table:
PersonId | PlaceName
---------+----------
1 | NULL
1 | NULL
2 | NULL
2 | Las Vegas
3 | London
4 | NULL
4 | NULL
4 | NULL
I'm looking for people who haven't bothered to fill in "place names", so I want my output to look like this:
PersonId
--------
1
4
I'll actually be joining some other tables in to pull out the info on each "miscreant" person, but the crux of my problem is the one above.
Upvotes: 1
Views: 92
Reputation: 247710
select distinct t1.id
from test t1
LEFT JOIN
(
select id, count(name) nm
from test
where name is not null
group by id
) x
on t1.id = x.id
where x.nm is null
Upvotes: 1
Reputation: 7093
SELECT DISTINCT PersonId
FROM MyTable t
WHERE NOT EXISTS(SELECT 1 FROM MyTable WHERE PersonId = t.PersonId AND PlaceName is not null)
Upvotes: 0
Reputation: 386
Use the following query:
SELECT PersonId
FROM TheTable
GROUP BY PersonId
HAVING COUNT(PlaceName) = 0
The COUNT()
aggregate function ignores NULL
s, so the right result should be returned.
Upvotes: 2
Reputation: 10184
I would offer the following:
select distinct a.personid
from tablename a
left outer join tablename b
on a.personid=b.personid
and b.placename is not null
where b.personid is null
order by personid
Upvotes: 0
Reputation: 171421
select PersonId
from MyTable
group by PersonId
having count(case when PlaceName is not null then 1 end) = 0
Upvotes: 1