我有以下代码和输出:
SELECT CustomerCategoryName, COUNT(a.CustomerID) AS CustomersInThisCategory
FROM Sales.Customers AS a
RIGHT JOIN Sales.CustomerCategories AS b on a.CustomerCategoryID = b.CustomerCategoryID
GROUP BY CustomerCategoryName
ORDER BY CustomersInThisCategory DESC
这会生成以下输出:
当我添加以下COUNT聚合函数和内部联接时:
SELECT CustomerCategoryName, COUNT(a.CustomerID) AS CustomersInThisCategory, COUNT(c.OrderID) AS Orders
FROM Sales.Customers AS a
RIGHT JOIN Sales.CustomerCategories AS b on a.CustomerCategoryID = b.CustomerCategoryID
INNER JOIN Sales.Orders AS c ON a.CustomerID = c.CustomerID
GROUP BY CustomerCategoryName
ORDER BY CustomersInThisCategory DESC
输出变为:
我不确定为什么CustomersInThisCategory列更改为与Orders列相同?我也不确定为什么在第二个查询中删除第一个输出0值的结果,因为我仍然存在右连接。
任何反馈都将非常感激。
对于您的第一个查询,count(distinct a.customerId)应该为您提供类别中的唯一客户ID。关于第二个问题,在内连接之前执行右连接。因此内部联接将拼接记录,但未找到匹配项。希望我的回答有所帮助