简体   繁体   English

计算 7 天平均值

[英]Calculating a 7 day average

I have this query.我有这个查询。

CREATE TABLE ip_logs (
  `ip_address` VARCHAR(11),
  `start_date` VARCHAR(11),
  `end_date` VARCHAR(11),
  `time_stamp`, VARCHAR(20),
  `mappings`, INTEGER,
  `loc_id` INTEGER
);

INSERT INTO ip_logs
  (`ip_address`,`start_date`,`end_date`,`time_stamp`,`mappings`, `loc_id`)
VALUES
 ('120.2.53.21','2020-01-03','2020-01-09','2020-01-03 14:33','2', '5'),
 ('198.3.222.2','2020-01-03','2020-01-14','2020-01-03 7:53', '7','4'),
 ('108.4.213.3','2020-01-04','2020-01-07','2020-01-04 12:13','3', '4'),
 ('128.5.173.4','2020-01-07','2020-02-15','2020-01-07 8:29', '12','3'),
 ('110.6.432.5','2020-01-07','2020-03-01','2020-01-07 11:45','4', '2'),
 ('198.7.222.6','2020-01-10','2020-01-14', '2020-01-10 17:32','8', '1'),
 ('118.8.113.7','2020-01-10','2020-01-19','2020-01-10 20:52','10', '4'),
 ('106.1.212.9','2020-02-24','2020-03-30','2020-02-24 10:08','5', '1'); 

I want to generate the 7 day average of the mappings column.我想生成映射列的 7 天平均值。 For example, I want to calculate the average mappings for each day (from 2020-01-03 - 2020-01-10).例如,我想计算每天的平均映射(从 2020-01-03 - 2020-01-10)。

Results:结果:

 time_stamp | avg_mapping
 2020-01-03 | 4.5 (2 + 7) /2
 2020-01-04 | 3
 2020-01-07 | 8 (12 +4)/2
 2020-01-10 | 9 

Then return avg(avg_mapping)然后返回 avg(avg_mapping)

I don't see how your question relates to a rolling average.我不明白你的问题与滚动平均值有什么关系。 From your data and results, it seems like you just want aggregation and avg() :从您的数据和结果来看,您似乎只想要聚合和avg()

select date(time_stamp) as time_stamp_day, avg(mapping) as avg_mapping
from ip_logs
group by date(time_stamp)

If you want the average of column avg_mapping in the resultset (which is not the same thing as an overall average of mapping ), then you can add another level of aggregation:如果您想要结果avg_mappingavg_mapping的平均值(这与mapping的整体平均值不同),那么您可以添加另一个级别的聚合:

select avg(avg_mapping) as avg_avg_mapping
from (
    select avg(mapping) as avg_mapping
    from ip_logs
    group by date(time_stamp)
) l

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM