简体   繁体   English

查找每天的平均值,如果当天没有记录,则取最新的平均值

[英]Find average per day, take latest if there is no record for the day

I'm not sure that the tile is correct nor specific.. 我不确定拼贴是否正确或特定。

I have a table that looks like this: 我有一个看起来像这样的表:

2013-01-01
a: 100

2013-01-02
b: 50

2013-01-03
c: 75
b: 200

Where "a, b, c" user ids. 其中“ a,b,c”用户标识。

I need a query that will return: 我需要一个查询,该查询将返回:

2013-01-01
100 / 1 = 100

2013-01-02
(100 + 50) / 2 = 75

2013-01-03
(100 + 200 + 75) / 3 = 125

[[2013-01-01, 100], [2013-01-02, 75], [2013-01-03, 125]] [[2013-01-01,100],[2013-01-02,75],[2013-01-03,125]]

It seems for a certein date I can do this with: 似乎可以在证书日期中通过以下方式执行此操作:

SELECT AVG(column1) FROM table a 
  JOIN (
   SELECT MAX(date) AS max_date, user_id FROM table 
     WHERE date < "2013-09-01" GROUP BY user_id) b 
   ON b.user_id = a.user_id AND a.date = b.max_date;

However, I have an interval which can be split by day, week, month or year: ['2013-01-01', '2013-01-02',... '2014-01-01'] (continuous) 但是,我的间隔可以按天,周,月或年划分:['2013-01-01','2013-01-02',...'2014-01-01'](连续)

Is there a faster way to do that instead of running 100 queries for a 100 day interval? 有没有一种更快的方法来代替以100天为间隔运行100个查询?

sqlfiddle: http://sqlfiddle.com/#!2/d74fa/2 sqlfiddle: http ://sqlfiddle.com/#!2/d74fa/2

Desired result: single query that will return 所需结果:将返回的单个查询

2013-01-01, 100
2013-01-02, 75
2013-01-03, 125

If you need the daily average you have to use: 如果您需要每日平均值,则必须使用:

SELECT AVG(value)
FROM readings r
GROUP BY(date);

I am not sure why you are doing the average up to the day in the analytical description. 我不确定您为什么要在分析说明中进行当天的平均计算。

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

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