从前一行按日期和ID减去当前的电流

时间:2017-03-30 17:40:21

标签: sql ms-access

我想通过将ID作为分组列来扩展此答案here。我尝试将一个'小组包括在内。条款没有成功。

+----------+--------------+----------
|NAV_Date  |NetAssetValue |  ID      |
+----------+--------------+---------+
|12/31/2012|        $4,000|     A     |
+----------+--------------+---------+
|03/31/2013|        $5,000|     A     |
+----------+--------------+---------+
|12/31/2012|        $4,000|     B     |
+----------+--------------+---------+
|03/31/2013|        $5,000|     B     |
+----------+--------------+---------+
select NAV_date, NAV_value, (NAV_value / prev_value) - 1
from (select t.*,
             (select top 1 NAV_value
              from YOURTABLENAMEGOESHERE as t2
              where t2.NAV_date < t.NAV_date
              group by Nav_ID, Nav_value
              order by t2.NAV_date desc
             ) as prev_value
      from YOURTABLENAMEGOESHERE as t
     ) as t

1 个答案:

答案 0 :(得分:1)

试试这个:

select 
    NAV_date, 
    NAV_value, 
    (NAV_value / 
        (select top 1 NAV_value
        from YOURTABLENAMEGOESHERE as t2
        where t2.NAV_date < t.NAV_date
        order by t2.NAV_date desc) - 1
from 
    YOURTABLENAMEGOESHERE as t