-2

我想根据以下数据知道每小时的使用量是多少:

TIME        DATA
00:00:24    3198
00:17:42    3199
00:44:54    3200
01:24:24    3201
01:52:24    3202
02:27:18    3203
02:51:06    3204
03:28:30    3205

当我使用如下查询时:

SELECT
    left(TIME,2) AS hour,
    max(DATA) - min(DATA) as usage
    FROM my_table
GROUP BY hour

我得到不正确的值,因为 MySQL 只查看小时范围内的最小值与最大值相比。结果是:

hour     usage
00       2
01       1
02       1
03       0

如果我手动查看数据并手动求和,我会期望:

TIME        DATA    Usage (summed by hand)
00:00:24    3198        
00:17:42    3199        
00:44:54    3200    2 
01:24:24    3201        
01:52:24    3202    3  
02:27:18    3203        
02:51:06    3204    2
03:28:30    3205    1

有没有办法直接在 MySQL 中解决这个问题,还是我需要在 PHP 中创建一个循环?(编辑查询并澄清结果和预期结果)

4

3 回答 3

1

尝试这个:

   select left(time, 2), count(*) from <your table name> group by left(time, 2)
于 2013-07-09T16:46:59.697 回答
0

检查以下查询:

SELECT A.TIME , A.DATA , CASE WHEN B.USAGE IS NULL THEN NULL ELSE USAGE END AS USAGE
FROM
USAGE AS A
LEFT OUTER JOIN
(
SELECT LEFT(TIME , 2) AS TIMEINHOUR ,  
MAX(TIME) AS MAXTIME , MAX(DATA) - MIN(DATA) AS USAGE
FROM USAGE
GROUP BY LEFT(TIME , 2)
) AS B ON A.TIME = B.MAXTIME
于 2013-07-09T17:50:19.540 回答
0

考虑这个解决方案:

SELECT LEFT(time, 2) AS `hour`, COUNT(LEFT(time, 2)) AS `count`
FROM tbl
GROUP BY `hour`

您必须替换tbl为您的表的名称。

于 2013-07-09T17:36:30.767 回答