我有以下表格(简化版):
CUSTOMERS
-int id
-varchar name
ENVENTS
-int id
-int customer_id
-int duration
我的问题是,我希望获得具有相同customer_id的持续时间总和,然后将customer_id替换为来自表客户的名称。
所以输出应该是:
+--------------+----------------+ | name | sum(durtaions) | +--------------+----------------+ | customername | 12313 | +--------------+----------------+
任何人都可以给我一个提示吗?
答案 0 :(得分:4)
尝试连接两个表并使用GROUP BY
子句来实现此目的:
SELECT c.name
,SUM(e.duration) AS duration
FROM Customers c
JOIN EVENTS e
ON c.id = e.customer_id
GROUP BY c.id
编辑:
如果客户名称不在事件表
中,请尝试LEFT JOIN
获取持续时间为0的客户名称
SELECT c.name
,IFNULL(SUM(e.duration),0) AS duration
FROM Customers c
LEFT JOIN EVENTS e
ON c.id = e.customer_id
GROUP BY c.id
答案 1 :(得分:1)
请尝试以下代码。
select c.name,SUM(e.duaration) as duration
from customer as c
left join events as e
on c.id = e.id
group by e.customer_id