MS Access - SQL Query for Average of Each Day Data

巧了我就是萌 提交于 2019-12-25 08:33:38

问题


I have a set of data spanning across 3 days. Based on the first column from the left, is it possible to have a query that calculates the average of the values in the third column from the left based on each day?

The end result will be two columns:

1/1/2008 | 1.605 
2/1/2008 | 1.59 
3/1/2008 | 1.56

I think the logic will be something like in a loop:

  • Based on the day in the first column, if it is the same day, count the number of rows and add up the values of the third column
  • Use the sum of the values of the third column and divide by the number of rows to get the Average
  • day + 1

But how can we implement a loop in MS Access?

Here is the set of data:

Edit: If I want to group by the date, where the day is between yesterday's 6PM to today's 6PM?

The BETWEEN clause is to check for records that are between yesterday's 18:00:00 and today's 18:00:00. Example, for 1/1/2008, the record will start from 1/1/2008 6:00PM to 2/1/2008 6:00PM. For 2/1/2008, the record will start from 2/1/2008 6:00PM to 3/1/2008 6:00PM`. So on and so forth...

I have a code snippet that checks for this:

([In process analysis result].[Date Time]) Between Date()-1+#12/30/1899 18:0:0# And Date()+#12/30/1899 18:0:0#)

But it only groups for one day before. How can I apply for the set of data?

Edit 2: This is the query that I have done, but it is still not correct. Any idea what is wrong?

SELECT DateValue([Date Time]) As DateValue, Avg([MFR g/10min]) AS [AvgOfMFR g/10min]
FROM [In process analysis result]
WHERE ((([Date Time])>Now()-365) AND (([Operation Grade-Load]) Like "EX*") AND (([Date Time]) Between [Date Time]-1+#12/30/1899 18:0:0# And [Date Time]+#12/30/1899 18:0:0#))
GROUP BY DateValue([Date Time]);

回答1:


SELECT the AVG of the value and GROUP BY the date




回答2:


Your logic looks basically correct. The where clause looks off. Start with this:

SELECT DateValue(DateAdd("h", 6, [Date Time])) As DateValue,
       Avg([MFR g/10min]) AS [AvgOfMFR g/10min]
FROM [In process analysis result]
WHERE [Date Time] > DateAdd("yyyy", -1, DateAdd("h", 6, Now())) AND
      [Operation Grade-Load] Like "EX*" 
GROUP BY DateValue(DateAdd("h", 6, [Date Time]));

I'm not sure what the BETWEEN condition is supposed to be doing. If you want a particular date range, just use date constants.

Edit: Date/time should be offset by 6 hours as in the above edit. And a proper 1-year-back expression should be used. Not sure if current time should be shifted 6 hours too (shown); if not, just remove the DateAdd of Now().



来源:https://stackoverflow.com/questions/41581378/ms-access-sql-query-for-average-of-each-day-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!