我有一张这样的表:
ID | Type | Value | Timestamp
--------------------------------
1 | AAA | 0.5 | day 1 hour 1
2 | BBB | 1.5 | day 1 hour 1
3 | CCC | 1.8 | day 1 hour 1
.....
11 | AAA | 0.6 | day 1 hour 2
12 | BBB | 1.4 | day 1 hour 2
13 | CCC | 1.5 | day 1 hour 2
.....
ID := Int, PK, AI, and so on
Type := String/Varchar
Value := Double
Timestamp := Unix Timestamp (Int), could be easily changed to date type
我想要的是现在特定时间范围的平均值。例如:
我希望所有AAA和所有BBB平均值为"值"第1天到第3天。 每天有几天每种类型有24个条目。
预期结果将是
Type | Average | Timestamp/Date
-------------------------------
AAA | 0.5242 | Day 1
AAA | 0.5442 | Day 2
AAA | 0.5913 | Day 3
BBB | 1.4228 | Day 1
BBB | 1.6924 | Day 2
BBB | 1.3018 | Day 3
我不确定这是否可以使用mysql。使用PHP可能会更有效率吗?
答案 0 :(得分:1)
这会产生您需要的结果吗?
# DROP TABLE IF EXISTS likeThis;
CREATE TABLE likeThis (id INT UNSIGNED, `type` CHAR(255), `value` DECIMAL(2,1), `timestamp` CHAR(255));
INSERT INTO likeThis VALUES
(1, 'AAA', 0.5, 'day 1 hour 1'),
(2, 'BBB', 1.5, 'day 1 hour 1'),
(3, 'CCC', 1.8, 'day 1 hour 1'),
(11, 'AAA', 0.6, 'day 1 hour 2'),
(12, 'BBB', 1.4, 'day 1 hour 2'),
(13, 'CCC', 1.5, 'day 1 hour 2');
SELECT * FROM likeThis;
SELECT type, AVG(`value`) average, LEFT(`timestamp`, INSTR(`timestamp`, 'hour') - 2) timestampDate FROM likeThis GROUP BY `type`, LEFT(`timestamp`, INSTR(`timestamp`, 'hour') - 2);
如果没有,请告诉我,
如果日期存储在不同的字段类型中,如何调整查询,以下是一些示例查询:
# How to aggregate by day on a DATETIME field type timestamp
SELECT type, AVG(`value`) average, DATE_FORMAT(`timestamp`, '%Y%m%d') timestampDate FROM likeThis GROUP BY `type`, DATE_FORMAT(`timestamp`, '%Y%m%d');
# How to aggregate by day on a unix timestamp (stored as INT) field type timestamp
SELECT type, AVG(`value`) average, `timestamp` - `timestamp` % 86400 timestampDate FROM likeThis GROUP BY `type`, `timestamp` - `timestamp` % 86400;
谢谢,
詹姆斯