我有两张如下定义的表格,
表:客户:
CustomerID | CustomerName |
--------------------------
1 | John
2 | Mack
3 | Andy
表:订单:
OrderID | CustomerID|
--------------------------
1515 | 1
1516 | 3
1517 | 1
1518 | 1
1519 | 3
1520 | 1
我想写一个查询来选择每个客户使用JOIN下的所有订单的每个名称和数量。结果将是,
John | 4
Mack | 0
Andy | 2
我的查询:
SELECT
CustomerName, Count(*)
FROM
Orders
INNER JOIN
Customers WHERE Orders.CustomerID = Customers.CustomerID;
但它返回的结果不正确。请指教。
答案 0 :(得分:1)
您错过了GROUP BY
。我会写这样的查询:
SELECT c.CustomerName, Count(o.CustomerId)
FROM Customers c LEFT JOIN
Orders o
ON o.CustomerID = c.CustomerID
GROUP BY c.CustomerName;
注意:
c
和o
)使查询更易于编写和阅读。LEFT JOIN
保留所有客户,即使是没有订单的客户。如果您不想要0
次,请更改为INNER JOIN
。ON
子句,而不是WHERE
条件的JOIN
子句。GROUP BY
来修复您的查询尝试。答案 1 :(得分:0)
使用:
SELECT Customers.CustomerName, Count(*)
FROM Orders LEFT OUTER JOIN Customers
WHERE Orders.CustomerID=Customers.CustomerID GROUP BY Customers.CustomerName;
答案 2 :(得分:0)
SELECT CustomerName,ISNULL(_Count,0) [Count]
来自客户 LEFT OUTER JOIN ( SELECT COUNT(*)_ Count,CustomerId _CustomerId 来自订单 GROUP BY CustomerId )ON _CustomerId = CustomerID