我有三个表: 顾客 -地区 -运营商
我需要找出每个运营商有多少客户。
select CarrierFirstName + ' ' + carrierlastname ' Carrier Name', CustomerID
from Carrier
inner join Route ON Carrier.CarrierID = Route.CarrierId
inner join Customer ON Customer.RouteID = Route.RouteID
group by carrier.CarrierFirstName, CarrierLastName, CustomerID
这给了我几次承运人的名字和每个不同的customerID,而我需要名字,然后是与每个名字相关的客户总数
Joe Johnson | 15|
Carrie Lan | 12|
答案 0 :(得分:1)
大概您只需要在这里计算:
SELECT
CarrierFirstName + ' ' + carrierlastname AS 'Carrier Name',
COUNT(*) AS num_customeres
FROM Carrier ca
INNER JOIN Route r
ON ca.CarrierID = r.CarrierId
INNER JOIN Customer cu
ON cu.RouteID = r.RouteID
GROUP BY
CarrierFirstName + ' ' + carrierlastname;
请注意,按承运人的姓名来汇总运营商是不理想的,因为两个人的姓氏和名字可以相同(我在世界上的某个地方甚至有一个双姓)。相反,通过Carrier
表中的某个主键进行聚合将是更好的策略。
我在查询中引入了别名,以便于阅读。
答案 1 :(得分:0)
您需要修复group by
。这也使用表别名来简化查询:
select (c.CarrierFirstName + ' ' + c.carrierlastname) as carrier_name,
count(*)
from Carrier c inner join
Route r
on c.CarrierID = r.CarrierId inner join
Customer cu
on cu.RouteID = r.RouteID
group by c.CarrierFirstName, c.CarrierLastName