MS Access-滚动YTD计算Sql查询

时间:2014-07-22 15:09:49

标签: sql ms-access-2007

试图找出如何使用SQL查询在Access 2010中实现YTD计算。 当前表:

Property date_rec(mm/dd/yyyy) Revenue month1 year1

    A    01/01/2013            100       01 2013
    A    02/01/2013            50        02 2013
    B    01/01/2014            200       01 2014
    B    02/01/2014            300       02 2014

期望的输出:

   Property date_rec   Revenue YTD_revenue
    A         01/01/2013 100     100
    A         02/01/2013 50      150
    B         01/01/2014 200     200
    B         02/01/2014 300     500

我们尝试了以下查询,但MS Access会引发错误:'您试图执行不包含指定表达式month1的查询作为聚合函数的一部分'

select test.property, test.date_rec, (select sum(test.revenue) 
                               from test a 
                              where a.month1<=b.month1 AND a.year1=b.year1) 
as revenue_ytd into new_table 
from test b
where a.date_rec=b.date_rec 
group by property, date_rec order by property, date_rec;

有人可以帮助我们调试代码或告诉我们我们是否做错了什么? :)

1 个答案:

答案 0 :(得分:0)

你很亲密。您只需要在group by子句中包含年份和月份:

select b.property, b.date_rec,
       (select sum(a.revenue) 
        from test as a 
        where a.month1 <= b.month1 AND a.year1 = b.year1 and
              a.property = b.property
       ) as revenue_ytd
into new_table 
from test as b
group by property, date_rec, month1, year1
order by property, date_rec;