如何基于约束各列来汇总各行

时间:2016-10-16 23:06:37

标签: mysql

我想为MySQL表上同一天的给定values的给定sensor添加所有machine。如果今天的日期是2016年10月17日,并且该表格包含以下数据:

+-------------------+---------+---------+---------+
|      timestamp    +  value  +  sensor | machine |
+-------------------+---------+---------+---------+
| 10/10/16 01:20:23 |   10    |    1    |    20   |   
| 10/10/16 02:33:05 |   23    |    1    |    20   |
| 11/10/16 03:14:40 |   17    |    1    |    20   |
| 11/10/16 05:53:00 |   99    |    1    |    20   |
| 11/10/16 06:29:20 |   32    |    1    |    20   |
| 11/10/16 07:10:28 |   23    |    2    |    20   |
| 11/10/16 10:00:05 |   45    |    1    |    20   |
| 12/10/16 03:30:00 |   12    |    1    |    20   |
| 12/10/16 14:00:43 |   10    |    1    |    20   |
| 12/10/16 16:40:12 |   89    |    1    |    20   |
| 12/10/16 20:00:45 |   87    |    1    |    20   |
| 12/10/16 23:42:23 |   24    |    2    |    20   |
| 13/10/16 14:02:00 |   97    |    1    |    20   |
| 14/10/16 03:03:04 |   04    |    1    |    20   |
| 14/10/16 15:56:00 |   12    |    1    |    20   |
| 15/10/16 22:18:23 |   93    |    1    |    20   |
| 16/10/16 12:29:45 |   23    |    1    |    20   |
+-------------------+---------+---------+---------+

我希望得到以下结论。

+-----------------+---------+---------+---------+
|    timestamp    +  value  + sensor  | machine |
+-----------------+---------+---------+---------+
|     10/10/16    |   33    |    1    |    20   |  
|     11/10/16    |   193   |    1    |    20   |  
|     12/10/16    |   198   |    1    |    20   |  
|     13/10/16    |   99    |    1    |    20   |  
|     14/10/16    |   16    |    1    |    20   |  
|     15/10/16    |   93    |    1    |    20   |  
|     16/10/16    |   23    |    1    |    20   |  
+-----------------+---------+---------+---------+

我想为给定的values添加给定sensor的所有machine,并按日期分组。我试过看example,但错误太多了。

问:我如何进行MySQL查询以获得此类输出?

2 个答案:

答案 0 :(得分:0)

您需要使用SUMGROUP BY

SELECT date, SUM(value) as value, sensor, machine
FROM my_table
WHERE senson=1 AND machine=20
GROUP BY date

您可以按多个列进行分组,例如,如果您需要所有传感器和计算机的表(而不是单个表),则可以使用:

SELECT date, SUM(value) as value, sensor, machine
FROM my_table
GROUP BY date, sensor, machine

答案 1 :(得分:0)

这将包含日期的所有值,并返回日期以及该特定日期的相应值的总和。

SELECT DATE(  `timestamp` ) DateOnly, SUM(  `value` ) AS  `value` ,  `sensor` ,  `machine` 
FROM my_table
WHERE  `sensor` = 3
AND  `machine` = 20
GROUP BY DateOnly,  `machine` ,  `sensor`

它将按日期分组。