dta38159 2017-08-18 06:13
浏览 56
已采纳

获取特定时间范围和特定条目类型的值的平均值

I have a table like this:

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

What I want is now an average for specific timeframes. For example:

I want all AAA and all BBB with an average of "Value" for day 1 till day 3. Every day has 24 entries per type over several days.

Expected result would be

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

I'm not sure if this is possible just with mysql. Maybe it's more efficient to do it with PHP?

  • 写回答

1条回答 默认 最新

  • dragonsun00000 2017-08-18 08:55
    关注

    Does this produce the result you require?

    # 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);
    

    Let me know if not,

    Regarding how to adapt the query if the date is stored in differing field types, here are some example queries:

    # 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;
    

    Thanks,

    James

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?