SQL Query仅查找2列中的唯一字符串

时间:2011-02-22 02:55:40

标签: sql database oracle

我有一个包含2列的表,两个都有名字

我想要一个只查找唯一名称的查询 - 只在整个表中出现一次的名称。

例如,对于下表:

NAME1    |     NAME2
--------------------
DAN             MIKE
MIKE            TONY
FOO              DAN

它应该只返回FOO和TONY。

由于

4 个答案:

答案 0 :(得分:2)

我想你可以通过几种方式做到这一点,但这里有一个(假设Name1和Name2属于相同或隐式可转换类型):

SELECT [Name]
FROM (SELECT Name1 AS [Name] FROM [Table] UNION ALL SELECT Name2 FROM [Table])
GROUP BY [Name]
HAVING COUNT(*) = 1

答案 1 :(得分:1)

简单如何:

select name1 from table where name1 not in (select distinct name2 from table ) 
union 
select name2 from table where name2 not in (select distinct name1 from table );

答案 2 :(得分:0)

只要name1name2不能为空,请使用以下查询:

SELECT t.Name1
FROM tableName t LEFT JOIN tableName t2 ON t.NAME1 = t2.NAME2
WHERE t2.NAME2 IS NULL
GROUP BY t.Name1
HAVING COUNT(*) = 1
UNION ALL
SELECT t.Name2
FROM tableName t LEFT JOIN tableName t2 ON t.NAME2 = t2.NAME1
WHERE t2.NAME1 IS NULL
GROUP BY t.Name2
HAVING COUNT(*) = 1

如果它们可以为null,请使用以下查询:

SELECT Name
FROM (
  SELECT t.Name1 Name
  FROM tableName
  GROUP BY t.Name1
  HAVING COUNT(*) = 1
  UNION ALL
  SELECT t.Name2 Name
  FROM tableName
  GROUP BY t.Name2
  HAVING COUNT(*) = 1
) rs
GROUP BY Name
HAVING COUNT(*) = 1

答案 3 :(得分:0)

@CheeseConQueso以不同于我的方式解释了这个问题。我认为你的意思是来自两个列的唯一名称。

这是我的版本:

select name, count(*) from (select name1 as name from table union select name2 as name from table) group by name having count(*) = 1;

您可以将整个事物包装在“从...中选择名称”以单独获取名称,或者可以使用分析函数重写,而不是使用分组来过滤重复项。取决于您的数据库的功能。