我正在尝试在SQL Server中编写一个查询,以查明customerID对每个客户是否有多行。 请告诉我。
这是表结构
Customer table
-----------------------------------------
orderID CustName CustomerID
---------------------------------------
100 test 123456
101 test 123456
Orders table
------------------------------------
pID OrderID
-----------------------------------
1 100
2 101
答案 0 :(得分:16)
您可以使用GROUP BY
查询来实现此目的:
select CustomerID, count(*) as NumDuplicates
from Customer
group by CustomerID
having count(*) > 1
答案 1 :(得分:5)
查看您拥有的每位客户的数量:
SELECT COUNT(*), CustName, CustomerID
from Customer
Group by CustName, CustomerID
您可以使用having
子句限制重复:
SELECT COUNT(*), CustName, CustomerID
from Customer
Group by CustName, CustomerID
having count(*) > 1
<强>更新强>
要获得订单成功的人:
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;
答案 2 :(得分:0)
select CustomerID, count(1)
from Customer
group by CustomerID
having count(1) > 1