我正在使用Northwind示例数据库中的Orders表。可在此处找到:http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_distinct
我正在尝试查找仅使用shipperID 3的唯一客户的数量。(因此,如果同一客户使用了shipperID 1或shipperID 2,我不想将他添加到计数中)
我知道我可以通过以下方式查询这些独特的客户:
SELECT CustomerID , ShipperID
FROM Orders
GROUP BY CustomerID
HAVING COUNT(DISTINCT ShipperID)=1 and shipperid = 3
但是我不确定如何实际获得不同CustomerID的总数。有人能帮我一把吗?谢谢:))
答案 0 :(得分:0)
select count (distinct customerid) from (SELECT CustomerID , ShipperID
FROM Orders
GROUP BY CustomerID
HAVING COUNT(DISTINCT ShipperID)=1 and shipperid = 3) as data ;
答案 1 :(得分:0)
从Customers表中进行选择,而不是从Orders表中进行选择。该表每个客户有一行,因此您可以更轻松地获得计数。您需要的条件是客户已使用ShipperID#3且客户未使用任何ShipperID<> 3.因此有两个与订单表相关的EXISTS条件。
SELECT COUNT(*)
FROM Customers
WHERE EXISTS (
SELECT *
FROM Orders
WHERE Orders.CustomerID = Customers.CustomerID
AND Orders.ShipperID = 3
) AND NOT EXISTS (
SELECT *
FROM Orders
WHERE Orders.CustomerID = Customers.CustomerID
AND Orders.ShipperID <> 3
)