SQL - 如何查找字段中仅包含1个值的记录

时间:2014-04-07 12:51:58

标签: sql select

我的表格看起来像这样:

member       value
0001         1
0001         2
0001         3
0002         1 
0002         2
0003         1

基本上我需要做的是检索成员3,因为它们只有一个值为1的记录。成员2具有值为1和2的记录,成员3具有值为1,2和3的记录。

请帮忙!

由于

罗布

6 个答案:

答案 0 :(得分:1)

这适用于Transact-SQL

SELECT member, value
  FROM TableName
  WHERE value IN
  (SELECT value FROM TableName
   GROUP BY value
   HAVING COUNT(*) = 1)

如果有多个成员只有一个条目,则会全部找到它们。

答案 1 :(得分:0)

我会将NOT EXISTScorrelated subquery

一起使用
SELECT t.member, t.value
FROM dbo.TableName t
WHERE value = 1
AND NOT EXISTS
(
    SELECT 1 FROM dbo.TableName t2
    WHERE t2.value <> 1
    AND   t.member = t2.member
)

Demo

如果您使用MS Sql-Server NOT EXISTS也是最有效的方法,在可空列上没有问题。值得一读:http://www.sqlperformance.com/2012/12/t-sql-queries/left-anti-semi-join

答案 2 :(得分:0)

select member
from (
select '0001' as member, 1 as value
union
select '0001' as member, 2 as value
union
select '0001' as member, 3 as value
union
select '0002' as member, 1 as value
union
select '0002' as member, 2 as value
union
select '0003' as member, 1 as value
) members
group by member
having count(*) = 1

答案 3 :(得分:0)

截至发布时间有很多复杂的答案,但使用GROUP BYHAVING可以很简单地回答问题:

select member
  from members_values
 group by member
having count(value) = 1

您还没有提到您使用的是哪种RDBMS而是AIUI,上述代码应该与ANSI兼容;它还假设您的表被称为members_values

答案 4 :(得分:0)

听起来你正在寻找只在该表中存在一次的member ......

member之后的以下查询分组,并证明member出现在表格中的次数

SELECT member
     , Count(*) As number_of_apperances
FROM   your_table
GROUP
    BY member

现在我们使用HAVING子句限制此聚合以仅显示仅出现一次的记录:

SELECT member
     , Count(*) As number_of_apperances
FROM   your_table
GROUP
    BY member
HAVING Count(*) = 1

答案 5 :(得分:0)

试试这个:

SELECT member
FROM MyTable
GROUP BY member
HAVING COUNT(value) = 1