0

编辑:我想我找到了解决方案,但我仍然想知道是否有人有更好的方法来做到这一点。添加“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) 列出不同的名称及其行数和总运行时间的总和

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)
4

1 回答 1

1

按名称字段分组是最好的解决方案:

SELECT
  Name,
  SUM(TIME_TO_SEC(TIMEDIFF(enddate,startdate))) TotalRunTime,
  COUNT(*) as TotalJobs
FROM results
WHERE name='name0'
GROUP BY Name;
于 2012-05-20T14:20:01.477 回答