获得一排客户

时间:2014-04-17 22:56:56

标签: mysql sum

如何获得每个客户的小时数? 我的数据看起来像这样

  Customer  |   Hours
   C1       |    15
   C1       |    13
   C3       |    23
   C4       |    10
   C4       |    5

客户和营业时间在一个单独的表格中。 我这样做了我的查询:

SELECT DISTINCT t2.Customer
FROM table1 t1
LEFT JOIN table2 t2
ON t1.id = t2.id
WHERE t2.Customer is not null
ORDER BY t2.Customer ASC

结果是

Customer
C1
C3
C4

我接下来要做的是总结客户的小时数,以便输出看起来像这样:

Customer   |    Hours
C1         |    28
C3         |    23
C4         |    15

1 个答案:

答案 0 :(得分:3)

你想要一个group by语句,如下所示:

SELECT t2.Customer, sum(t1.hours) as hours
FROM table1 t1 LEFT JOIN
     table2 t2
     ON t1.id = t2.id
WHERE t2.Customer is not null
GROUP BY t2.Customer
ORDER BY t2.Customer ASC;