简体   繁体   English

在多个表中查找计数

[英]Finding count in multiple tables

I need to find the amount of times a customer appears in the Orders and Requests tables respectively. 我需要查找客户分别在“订单”和“请求”表中出现的次数。 However this script is producing the same count value for both places where COUNT is used. 但是,此脚本在使用COUNT的两个地方产生相同的计数值。 The value cannot possibly be the same so what am I doing wrong? 该值可能无法相同,那么我在做什么错呢?

  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

You are multiplying the number of order and request records. 您正在乘以订单和请求记录的数量。 Ie by joining the tables, you get for, say, 3 orders and 4 requests for a customer 12 result rows. 即,通过加入表,您获得了12个结果行的3个订单和4个客户请求。 As the IDs will never be null in a record, COUNT(o.CustomerID) and COUNT(r.CustomerID) are just COUNT(*) (12 in my example, and not 3 and 4 as you expected). 由于ID在记录中永远不会为空,因此COUNT(o.CustomerID)COUNT(r.CustomerID)只是COUNT(*) (在我的示例中为12,而不是您期望的3和4)。

The easiest approach: 最简单的方法:

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;

The same with subqueries (derived tables) in the from clause: 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;

When aggregating from multiple tables, always aggregate first and join then. 从多个表进行聚合时,请始终先聚合然后再合并。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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