【发布时间】:2020-04-20 15:56:36
【问题描述】:
SQLite 数据库是here
我的问题是,每位员工支持了多少客户,每次销售的平均收入是多少,他们的总销售额是多少?
为了让每个员工支持多少客户,我的代码是这样的,
SELECT employees.EmployeeId, customers.SupportRepId, COUNT(customers.CustomerId) "Customers supported"
FROM customers
JOIN employees ON employees.EmployeeId = customers.SupportRepId
GROUP BY customers.SupportRepId;
我得到的结果是这样的:
+------------+--------------+----------------------+
| EmployeeID | SupportRepID | Customers Supported |
+------------+--------------+----------------------+
| 3 | 3 | 21 |
| 4 | 4 | 20 |
| 5 | 5 | 18 |
+------------+--------------+----------------------+
为了获得总收入和平均收入,我更新了如下代码:
SELECT employees.EmployeeId, customers.SupportRepId, COUNT(customers.CustomerId) 'Customers Supported', SUM(invoices.Total) 'Total Revenue', SUM(invoices.Total)/COUNT(customers.CustomerId) 'Average Revenue'
FROM customers
JOIN employees ON employees.EmployeeId = customers.SupportRepId
JOIN invoices ON invoices.CustomerId = customers.CustomerId
GROUP BY customers.SupportRepId;
我得到的结果是这样的:
+------------+--------------+---------------------+------------------+------------------+
| EmployeeID | SupportRepID | Customers Supported | Total Revenue | Average Revenue |
+------------+--------------+---------------------+------------------+------------------+
| 3 | 3 | 146 | 833.040000000001 | 5.70575342465754 |
| 4 | 4 | 140 | 775.400000000001 | 5.53857142857144 |
| 5 | 5 | 126 | 720.160000000001 | 5.71555555555556 |
+------------+--------------+---------------------+------------------+------------------+
更新我的代码后,支持的客户列发生了变化,我相信之前的数据是正确的。因此,我的平均收入与新值不正确。为什么客户支持的数据会发生变化?我该如何解决这个问题?
【问题讨论】:
-
“支持的客户”列不是直接表数据,而是计算为
customers.CustomerId的 COUNT。当您以不同方式连接表时,该计数不同,因此显示的值也不同。 -
那我该如何解决呢?
-
我没有机会仔细查看您链接的表模式。但是您可以尝试
COUNT(distinct customer.CustomerId),因为问题很可能是您计算了重复的客户 ID。 -
DISTINCT 函数有效。谢谢。