2012-10-30 51 views
77

我需要運行select語句,該語句返回列值不明顯的所有行(例如EmailAddress)。如何選擇列值不相同的每行行

例如,如果表看起來象下面這樣:

CustomerName  EmailAddress 
Aaron   [email protected] 
Christy   [email protected] 
Jason   [email protected] 
Eric    [email protected] 
John    [email protected] 

我需要查詢返回:

Aaron   [email protected] 
Christy   [email protected] 
John    [email protected] 

我已經看了很多帖子,並嘗試不同的查詢無果。我相信應該可以工作的查詢如下。有人可以提出一個替代方案或告訴我什麼可能是我的查詢錯?

select EmailAddress, CustomerName from Customers 
group by EmailAddress, CustomerName 
having COUNT(distinct(EmailAddress)) > 1 

回答

139

這比EXISTS方式顯著快:

SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN 
    (SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1) 
9

如何

SELECT EmailAddress, CustomerName FROM Customers a 
WHERE Exists (SELECT emailAddress FROM customers c WHERE a.customerName != c.customerName AND a.EmailAddress = c.EmailAddress) 
4

只是爲了好玩,還有一種方法:

;with counts as (
    select CustomerName, EmailAddress, 
     count(*) over (partition by EmailAddress) as num 
    from Customers 
) 
select CustomerName, EmailAddress 
from counts 
where num > 1 
+0

+1對於CTE版本 我們不應該在代碼中重複自己,爲什麼在SQL中重複自己,如果我們不再需要的話。 – yzorg

+0

我使用_count作爲count列(超過num)。當列發生與_default,_type,_sum等SQL關鍵字碰撞時,我一直使用下劃線。 – yzorg

23

這是不正確使用您的查詢的事情是,你是通過電子郵件,姓名等分組,即形成一組每組獨特的電子郵件和名稱組合在一起,因此

aaron and [email protected] 
christy and [email protected] 
john and [email protected] 

被視爲3個不同的組,而全部屬於1個單一組。

請使用下面的查詢給出:

select emailaddress,customername from customers where emailaddress in 
(select emailaddress from customers group by emailaddress having count(*) > 1) 
+5

我喜歡這一點,您還包括了有關原始查詢出現問題的解釋,與接受的答案不同。 – 2016-02-05 08:20:09

6
select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1 
+0

次要增加顯示計數爲「dups」:選擇CustomerName,計數(1)作爲來自Customers組的憑藉CustomerName具有計數(1)> 1' – DynamicDan

-1

以及有一個細微的變化,以尋找非重複行..

SELECT EmailAddress,CustomerName FROM Customers WHERE EmailAddress NOT IN(*)> 1)

0

而不是在where條件下使用子查詢,這將增加查詢時間,其中記錄是巨大的。

我建議使用Inner Join作爲這個問題的更好選擇。

考慮到同一個表,這可能給結果

SELECT EmailAddress, CustomerName FROM Customers as a 
Inner Join Customers as b on a.CustomerName <> b.CustomerName and a.EmailAddress = b.EmailAddress 

爲了得到更好的結果我會建議你使用CustomerID或你的表的任何唯一的領域。重複CustomerName是可能的。

相關問題