ms访问比较值与平均七天的平均值

时间:2014-04-02 17:11:05

标签: sql ms-access

我有一个包含人,日期,食物和食物数量的数据集。我想要一个查询,我指定一个人和一个日期,并返回两个值:在所选日期食用的食物数量和过去7天内食用的平均食物数量。

所以,如果我在2013年1月10日选择安倍,我得到“1”和“3.6”,因为他在1/10上吃了1片水果,在1/3到1之间平均每天吃3.6件水果/ 9。

名,thedate,数量,食物

name,thedate,qty,food
abe,1/2/2013,1,orange
abe,1/2/2013,3,pear
abe,1/3/2013,3,orange
abe,1/4/2013,2,orange
abe,1/4/2013,2,plum
abe,1/5/2013,1,orange
abe,1/7/2013,7,onion
abe,1/8/2013,2,orange
abe,1/9/2013,3,orange
abe,1/9/2013,2,pear
abe,1/10/2013,1,orange
jen,1/1/2013,2,orange
jen,1/4/2013,3,orange
jen,1/5/2013,2,orange

1 个答案:

答案 0 :(得分:2)

您需要一个相关的子查询才能找到这个

Select 
  Parent.name
  , Parent.thedate
  , Parent.qty, 
(SELECT avg(qty)
  FROM yourTable
  where name = parent.name  
     and thedate < parent.theDate 
     and theDate>=dateadd("d", datediff("d",0, parent.theDate)-7,0) 
  group by name) as previousSeven
from yourTable Parent

如果这实际上是基于每个水果类型,您也可以使用and fruit = parent.fruit加入group by}

<强>更新

要查找,而不是平均值,但水果数量的总和除以过去7天内数据的不同天数,您将需要更多这样的东西(它会变得更加复杂,因为访问权限不支持Select count(distinct something)语法)

Select
Name
, theDate
, qty
, sumOfPreviousSeven/distinctDaysWithDataLastSeven
from (
    Select 
      Parent.name
      , Parent.thedate
      , Parent.qty
    , (SELECT sum(qty)
      FROM table4
      where name = parent.name  
         and thedate < parent.theDate 
         and theDate>=dateadd("d", datediff("d",0, parent.theDate)-7,0) 
      group by name) as sumOfPreviousSeven

    , (select top 1 count(distinctDates) from 
            (select dateadd("d", datediff("d",0, theDate),0) as distinctDates, name  from table4
        group by dateadd("d", datediff("d",0, theDate),0), name)
        where name = parent.name 
            and  distinctDates < parent.theDate 
            and distinctDates>=dateadd("d", datediff("d",0, parent.theDate)-7,0) 
        group by name) as distinctDaysWithDataLastSeven
from table4 Parent) as base