SQL Server 2008 - 累积列

时间:2013-10-18 12:47:34

标签: sql sql-server sql-server-2008 accumulate

我想积累我的数据,如下所示,有原始表table1

  1. 这样做的最佳查询是什么?
  2. 当我添加更多类型的术语时,可以动态地执行此操作吗?
  3. 表1

    ID  |  term  |  value
    -----------------------
    1   |   I    |   100
    2   |   I    |   200
    3   |   II   |   100
    4   |   II   |    50 
    5   |   II   |    75
    6   |   III  |    50
    7   |   III  |    65
    8   |   IV   |    30
    9   |   IV   |    45
    

    结果如下:

    YTD  | Acc Value
    ------------------
    I-I  |   300
    I-II |   525
    I-III|   640
    I-IV |   715
    

    由于

1 个答案:

答案 0 :(得分:3)

    select 
        (select min(term) from yourtable ) +'-'+term,       
        (select sum(value) from yourtable  t1 where t1.term<=t.term)
    from yourtable t 
    group by term