我想知道每小时的使用量是基于以下数据:
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中创建一个循环? (编辑查询和澄清结果及预期结果)
答案 0 :(得分:1)
试试这个:
select left(time, 2), count(*) from <your table name> group by left(time, 2)
答案 1 :(得分:0)
考虑这个解决方案:
SELECT LEFT(time, 2) AS `hour`, COUNT(LEFT(time, 2)) AS `count`
FROM tbl
GROUP BY `hour`
您必须将tbl
替换为您的表格名称。
答案 2 :(得分: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