如何在SQL中统计客户的子数据

时间:2017-03-30 09:06:13

标签: sql

我有以下客户表

CustomerId     CustomerName   CustomerEmail
1              AAA            AAA@AAA.com
2              BBB            BBB@BBB.BBB   

这是我展示的示例数据。像这样我在customer表中有50000名客户,现在他们的发票也存储在invoice表中

InvoiceId      InvoiceAmount   InvoiceCustomerID
1              22.00           1
2              58.00           2
3              21.00           2
4              45.00           2

现在,我想在显示客户列表时计算每个客户的发票,例如:

CustomerId     CustomerName   CustomerEmail  TotalInvoice
1              AAA            AAA@AAA.com    1
2              BBB            BBB@BBB.BBB    3

我使用了以下查询,但没有工作

SELECT customer.*,COUNT(invoice.InvoiceId) FROM `customer` as customer INNER JOIN invoice as invoice ON customer.CustomerId= invoice.InvoiceCustomerID

可以建议任何方法来解决这个问题吗?

此外还有5个缺少发票,因此需要花费很多时间才能加载。

4 个答案:

答案 0 :(得分:1)

SELECT a.CustomerID, a.CustomerName, a.CustomerEmail,
SUM(CASE WHEN b.InvoiceID IS NOT NULL THEN 1 ELSE 0 END) as TotalInvoice
FROM `customer` a LEFT JOIN invoice b ON a.CustomerId= b.InvoiceCustomerID
GROUP BY a.CustomerId, a.CustomerName, a.CustomerEmail

只需使用GROUP BY 此外,您是否需要显示没有发票的客户?如果你这样做,你将不得不把它变成左连接。

答案 1 :(得分:1)

您不能使用没有GROUP BY的分组功能:

SELECT customer.CustomerID, customer.Customer.Name, customer.CustomerEmail
    ,COUNT(invoice.InvoiceId) AS RC
FROM `customer` AS customer
INNER JOIN invoice AS invoice ON customer.CustomerId = invoice.InvoiceCustomerID
GROUP BY  customer.CustomerID, customer.Customer.Name, customer.CustomerEmail

答案 2 :(得分:0)

select c.CustomerId "CustomerId", 
c.CustomerName "CustomerName", 
c.CustomerEmail "CustomerEmail", 
count(i.InvoiceCustomerID) "TotalInvoice"  
from customer as c 
inner join invocie i 
on(i.InvoiceCustomerID = c.CustomerId) group by
c.CustomerId, c.CustomerName, c.CustomerEmail order by CustomerId

答案 3 :(得分:0)

由于批量数据,其他查询需要花费很长时间才能加载

所以我使用以下查询解决了这个问题

SELECT c.CustomerId,c.CustomerName,totalinvoice AS ttlinv FROM customer 
as c LEFT JOIN (select COUNT(InvoiceId) as totalinvoice,InvoiceCustomerID 
from invoice GROUP by InvoiceCustomerID) as io on io.InvoiceCustomerID=c.CustomerId