1

我正在绞尽脑汁想弄清楚什么组和/或不同的组和count()形成对此有帮助,但目前还一片空白。

考虑下表:

PersonId | PlaceName
---------+----------
    1    |   NULL
    1    |   NULL
    2    |   NULL
    2    | Las Vegas
    3    | London
    4    |   NULL
    4    |   NULL
    4    |   NULL

我正在寻找那些懒得填写“地名”的人,所以我希望我的输出看起来像这样:

PersonId
--------
    1
    4

实际上,我将加入其他一些表格以提取每个“不法之徒”的信息,但我的问题的症结在于上面的那个。

4

5 回答 5

2

使用以下查询:

SELECT PersonId
  FROM TheTable
 GROUP BY PersonId
 HAVING COUNT(PlaceName) = 0

COUNT()聚合函数忽略s,因此NULL应该返回正确的结果。

于 2012-08-09T16:19:23.667 回答
1
select PersonId
from MyTable
group by PersonId
having count(case when PlaceName is not null then 1 end) = 0

SQL 小提琴示例

于 2012-08-09T16:14:03.013 回答
1
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

请参阅带有演示的 SQL Fiddle

于 2012-08-09T16:16:31.050 回答
0

我会提供以下内容:

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
于 2012-08-09T16:15:58.673 回答
0
SELECT DISTINCT PersonId
FROM MyTable t
WHERE NOT EXISTS(SELECT 1 FROM MyTable WHERE PersonId = t.PersonId AND PlaceName is not null)
于 2012-08-09T16:30:08.240 回答