Question

I am using the Orders Table in the Northwind sample database. It can be found here: http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_distinct

I am trying to find the number of unique Customers that have only used shipperID 3. (so if the same Customer used shipperID 1 or shipperID 2 I don't want to add him to the count)

I know I can query for these unique Customers by doing:

SELECT CustomerID , ShipperID FROM Orders GROUP BY CustomerID HAVING COUNT(DISTINCT ShipperID)=1 and shipperid = 3

However I am not sure how to actually get the total count of distinct CustomerIDs. Could anyone give me hand? Thanks :)

Était-ce utile?

La solution

select count (distinct customerid)  from (SELECT CustomerID , ShipperID
FROM Orders
GROUP BY CustomerID
HAVING COUNT(DISTINCT ShipperID)=1 and shipperid = 3) as data ;

Autres conseils

Make your selection from the Customers table, instead of from the Orders table. That table has one row per customer, so you can get the count more easily. The condition you want is that the customer has used ShipperID #3 and the customer has not used any ShipperID <> 3. So there are two EXISTS conditions correlated to the Orders table.

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
)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top