我需要找到客户分别出现在订单和请求表中的次数。但是,此脚本为使用COUNT的两个位置生成相同的计数值。价值可能不一样,所以我做错了什么?
SELECT o.CustomerID,
COUNT(o.CustomerID) as OrdersPerCustomer,
COUNT(r.CustomerID) as RequestsPerCustomer
FROM Orders o
INNER JOIN [Customers] c on c.ID = o.CustomerID
INNER JOIN [Request] r on r.CustomerID = c.ID
GROUP BY o.CustomerID
答案 0 :(得分:1)
您将订单和请求记录的数量相乘。即通过加入表格,您可以获得3个订单和4个客户12个结果行的请求。由于ID在记录中永远不会为空,COUNT(o.CustomerID)
和COUNT(r.CustomerID)
只是COUNT(*)
(在我的示例中为12,而不是预期的3和4)。
最简单的方法:
select
customer_id,
(select count(*) from orders o where o.customerid = c.id) as o_count,
(select count(*) from request r where r.customerid = c.id) as r_count
from customers c;
与from子句中的子查询(派生表)相同:
select
customer_id,
coalesce(o.total, 0) as o_count,
coalesce(r.total, 0) as r_count
from customers c
left join (select customerid, count(*) as total from orders group by customerid) o
on o.customerid = c.id
left join (select customerid, count(*) as total from request group by customerid) r
on r.customerid = c.id;
从多个表聚合时,始终先聚合然后加入。