【发布时间】:2018-09-02 00:34:49
【问题描述】:
我的invoices 表有orderId 列,这是一个引用orderId primary key column of orders table 的外键,而订单表有customerId 列,它引用了客户表的customerId 主键列。
一个客户可以有多个订单,但一个订单只有一张发票。
我想计算每个客户的发票数量。以下是我尝试过的查询:
SELECT customers.name, COUNT(*) as number_of_invoices
FROM invoices
JOIN orders
ON invoices.orderId = orders.orderId
JOIN customers
ON orders.customerId = customers.customerId;
但它只返回一个客户,并且计数是该客户的总计数而不是发票计数。
【问题讨论】:
-
你需要在最后加上
GROUP BY customers.name。 -
@Brainy Prb 如果你觉得这个解决方案有用,那么请接受我的回答。