2016-12-01 72 views
0

我发现了很多关于选择独特的问题,但并未完全忽略非唯一。SQL Server - 不要选择,如果不是唯一的

我不只想要每个值的第一个值,我希望主动避免出现多次出现的值的所有记录。

MyTable 
id | col1 | col2 
1 | a | Some thing 
2 | b | Stuff 
3 | b | Other stuff 
4 | c | Some other thing 

SELECT * FROM MyTable WHERE [col1 is unique] 

应在col1b出现不止一次返回行1和4只,因为。

回答

6

内选择只得到col1是独一无二的。要获得完整的行,你需要使用外选择以及

select * from your_table 
where col1 in 
(
    select col1 
    from your_table 
    group by col1 
    having count(*) = 1 
) 
+4

@Matt。 。 。您的评论没有意义。 Juergen的答案对我来说看起来是正确的(可能有一个单例NULL值的例外,但假设不是''NULL'是合理的)。 –

+0

@GordonLinoff约定 – Sami

+0

@GordonLinoff我从来没有说过它不起作用,实际上我明确表示它确实有问题,我在回答中提到“你也需要使用外部选择”的部分问题,因为你不'实际上需要给出OP正在寻找独特的记录。如果寻找重复/非独特,那么这种技术将更加需要。当使用MAX或MIN等其他列的聚合来寻找唯一的唯一值时,我会回答这个问题以显示可能性。 – Matt

3

试试这个

with tmp as (
select f1.*, count(*) over(partition by col1 order by col1) nb 
from MyTable f1 
) 
select * from Mytable f2 inner join tmp f3 
on f2.id=f3.id and f3.nb=1 

select * from (
     select f1.*, count(*) over(partition by col1) nb 
     from MyTable f1 
      ) f2 
where f2.nb=1 

with tmp as (
select col1 from MyTable 
group by col1 
having count(*)=1 
) 
select * from MyTable f1 
where exists 
(
select * from tmp f2 
where f1.col1=f2.col1 
) 
2

Esperento57's answer它使用COUNT(*) OVER同意。但是因为你想要Col1是唯一的记录,所以你可以在一个单独的group by中进行聚合。

DECLARE @MyTable AS TABLE (id INT, col1 CHAR(1), col2 VARCHAR(100)) 
INSERT INTO @MyTable VALUES (1,'a','Some thing'),(2,'b','Stuff'), 

(3,'b','Other stuff'),(4,'c','Some other thing') 

SELECT 
    MIN(Id) as Id 
    ,Col1 
    ,MIN(col2) as col2 
FROM 
    @MyTable 
GROUP BY 
    Col1 
HAVING 
    COUNT(*) = 1 
+0

注意:并非所有的数据类型都可以在这里使用。哪些类型工作并不取决于正在使用的SQL Server版本。 – hvd

+1

为什么你应该说你**在回答中投了**? – Sami

+0

@Sami我正在展示一个替代Juergen来证明一个观点。我的偏好以及我通常会建议的是Esperrento回答的COUNT(*)OVER,并且我清楚地说明了这一点。您现在评论了一些通用评论,而不是关于答案是否正确,错误或需要调整的问题,特别是有什么困扰您的东西? – Matt

1

我认为最简单的方法就是使用窗函数:

SELECT t.* 
FROM (SELECT t.*, COUNT(*) OVER (PARTITION BY col1) as cnt 
     FROM MyTable t 
    ) t 
WHERE cnt = 1; 

如果您对表的主键,那么最快的方法(用适当的指数)可能是:

select t.* 
from MyTable t 
where not exists (select 1 from mytable t2 where t2.col = t.col and t2.pkid <> t.pkid); 

为此,您需要MyTable(col, pkid)上的索引。

+1

已经在我的回复中;) – Esperento57