mysql在一个表中汇总多组数据

时间:2012-05-20 14:09:56

标签: mysql group-by sum

编辑:我想我找到了解决方案,但我仍然有兴趣知道是否有人有更好的方法来做到这一点。添加“GROUP BY name”会产生正确的输出。

我有一张这样的表:

Name    StartDate             EndDate
name0   2012-05-18 20:00:00   2012-05-18 20:00:01
name1   2012-05-18 20:00:00   2012-05-18 20:00:05
name0   2012-05-18 20:00:00   2012-05-18 20:00:01
name3   2012-05-18 20:00:00   2012-05-18 20:00:03
name4   2012-05-18 20:00:00   2012-05-18 20:00:07
name3   2012-05-18 20:00:00   2012-05-18 20:00:03
name8   2012-05-18 20:00:00   2012-05-18 20:00:12
name5   2012-05-18 20:00:00   2012-05-18 20:00:11
name1   2012-05-18 20:00:00   2012-05-18 20:00:05

我正在努力学习如何做两件事:

1)列出不同的名称及其行的COUNT和总运行时间的总和

Name    Count   TotalRunTime
name0   2       2
name1   2       10
name3   2       6
name4   1       7
name5   1       11
name8   1       12

我创建了以下查询以尝试同时执行这两项操作。它适用于单个名称,但我无法弄清楚如何使其“迭代”在表格中的不同名称列表中。

SELECT
  Name,
  SUM(TIME_TO_SEC(TIMEDIFF(enddate,startdate))) TotalRunTime,
  COUNT(*) as TotalJobs
FROM results
WHERE name='name0';

产生:

+-------+-------------+-----------+
| Name  |TotalRunTime | TotalJobs |
+-------+-------------+-----------+
| name0 |     1023491 |        46 |
+-------+-------------+-----------+
1 row in set (0.00 sec)

但我想要的是:

+-------+-------------+-----------+
| Name  |TotalRunTime | TotalJobs |
+-------+-------------+-----------+
| name0 |     1023491 |        46 |
| name1 |      971621 |        35 |
| name3 |      108843 |        22 |
| ...   |         ... |       ... |
+-------+-------------+-----------+
<N> rows in set (0.00 sec)

1 个答案:

答案 0 :(得分:1)

Group BY name字段是最佳解决方案:

SELECT
  Name,
  SUM(TIME_TO_SEC(TIMEDIFF(enddate,startdate))) TotalRunTime,
  COUNT(*) as TotalJobs
FROM results
WHERE name='name0'
GROUP BY Name;