2016-12-01 31 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