2011-12-22 53 views
3

我需要基於單列(本例中爲代碼)獲得不同行,其中列值是重複的。連同來自行的其他信息和重複行的數量一起。例如:基於單列獲取重複的行和計數

ID  code  ownerName 
-------------------------- 
1  001  Mr. Brown 
2  001  Mr. Pink 
3  002  Mr. White 
4  003  Mr. Blonde 

我需要這個查詢返回

ID  code  ownerName count 
---------------------------------- 
1  001  Mr. Brown  2 

重複行的信息並不重要變回來了,但我有麻煩了不同的代碼與計列組合。

我已經嘗試了這樣的查詢:

SELECT DISTINCT A.code, A.ownerName 
FROM Customers A WHERE 
    EXISTS(SELECT * FROM Customers WHERE code = A.code AND id <> A.id) 
order by A.code; 

,但我遇到麻煩計數;並與此查詢

SELECT code, COUNT(*) as numberDuplicates 
FROM Customers GROUP BY code HAVING COUNT(*) > 1 

我無法獲得其他信息,我不想分組。任何人都可以幫助我弄清楚如何構建正確的查詢?

回答

9

如果我知道你在找什麼,這應該工作:

這將選擇所有條目與非唯一代碼,並返回使用該代碼的記錄數。

SELECT DISTINCT A.ID, A.Code, A.ownerName, B.Count 
FROM Customers A 
JOIN (
    SELECT COUNT(*) as Count, B.Code 
    FROM Customers B 
    GROUP BY B.Code 
) AS B ON A.Code = B.Code 
WHERE B.Count > 1 
ORDER by A.Code; 
+0

是的,這正是我一直在尋找,我只是說B.count到選擇列表中。謝謝。 – user501211 2011-12-22 18:45:10

0

我想你可以嘗試像下面

 SELECT TOP 1 C.ID, C.Code, C.OwnerName, C1.NumberDuplicates 
     FROM 
     Customers C 
     INNER JOIN 
     (
     SELECT Code, COUNT(*) as NumberDuplicates FROM Customers GROUP BY code HAVING COUNT(*) > 1 
     ) C1 
     ON C.Code = C1.Code 

希望這有助於!

0
SELECT COUNT(DISTINCT CustomerID) AS NumberOfCustomers FROM Orders;