2010-06-30 218 views
4

我正試圖在SQL服務器中編寫一個查詢,以查明每個客戶的customerID是否有多行。 請讓我知道。帶有重複記錄的SQL查詢

這裏是表結構

Customer table 
----------------------------------------- 
orderID   CustName  CustomerID 
--------------------------------------- 
100    test   123456  
101    test   123456 

Orders table 
------------------------------------ 
pID    OrderID 
----------------------------------- 
1     100   
2     101 
+5

如果你在一個地方是改變設計,請注意你的問題來源於顧客表中存在的'重複組'(谷歌'數據庫標準化')。假設每個訂單僅由一個客戶完成,一個更明智的方法是將CustomerID放入Order表中,而不是Customer表中的OrderID。 – grossvogel 2010-06-30 18:31:23

回答

14

您可以使用GROUP BY查詢來實現這一目標:

select CustomerID, count(*) as NumDuplicates 
from Customer 
group by CustomerID 
having count(*) > 1 
+0

訂單表中還有一個成功標誌。我想通過訂單表成功標誌爲1的customerID獲取所有行。 – nav100 2010-06-30 18:35:11

+0

@ nav100:您應該更新問題並添加此新要求。它改變了查詢。 – FrustratedWithFormsDesigner 2010-06-30 18:53:12

0
select CustomerID, count(1) 
    from Customer 
group by CustomerID 
having count(1) > 1 
+0

@OMG Ponies:實際上,這是計數常數1不是序數......(至少在SQL Server中)。另外,SUM(1)會做什麼? – gbn 2010-06-30 18:31:53

+0

@OMG小馬:1在這裏用作常量。 – 2010-06-30 18:33:33

+0

對不起,以爲這是序號。我總是使用列或* ... – 2010-06-30 18:46:48

4

要看看有多少每個客戶的您有:

SELECT COUNT(*), CustName, CustomerID 
from Customer 
Group by CustName, CustomerID 

您可以使用having子句限制只是重複:

SELECT COUNT(*), CustName, CustomerID 
from Customer 
Group by CustName, CustomerID 
having count(*) > 1 

UPDATE

要獲得那些成功的訂單:

select count(*), CustName, CustomerID 
from(
    SELECT CustName, CustomerID 
    from Customer, orders 
    where customer.orderID = orders.orderID 
    and orders.success = 1) subquery 
group by subquery.CustName, subquery.CustomerID 
having count(*) > 1; 
+0

這是我想出的查詢。但它是2個查詢。 從客戶選擇客戶ID select * from訂單ID (從客戶選擇OrderId,其中customerID = 123456) 且成功= 1 – nav100 2010-06-30 18:44:41