简体   繁体   中英

SQL: count values in one table based on WHERE from other table

I am not sure, why this is not working.

I have two simple tables:

Orders
OrderTypeID EmployeeID   Completion_needed
10308       72             15%
10309       73             20%
10310       74             30%

Customers
Customer ID   OrderTypeID   OrderDate    Order_completed
    1          10308       2015-09-18          5%
    2          10309       2015-09-19          30%
    3          10310       2017-09-20          25%
    4          10308       2015-09-18          17%
    2          10308       2015-09-19          20%
    3          10309       2017-09-20          7%

I want to calculate how many customers have non completed orders, where Order_completed in the Customers table is less than Completion_needed in the Orders table (please not that a customer can have more than one order type).

This is my query, but I get the wrong result:

SELECT COUNT(c.CustomerID) as count_employees
FROM Orders od
JOIN Customers c
ON od.OrderTypeID = c.OrderTypeID
WHERE od.Completion_needed > c.Order_completed

I get 1; but I should get the count of 2.

I don't see how you get "1" from your query. I see it producing "3". So, I think what you need is COUNT(DISTINCT) :

  SELECT COUNT(DISTINCT c.CustomerId)
  FROM Orders od JOIN
       Customers c
       ON od.OrderTypeID = c.OrderTypeID
  WHERE c.Order_completed < od.Completion_needed;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM