我怎样才能得到 'costs' 每年+之前所有年份的总和?

How can I get the SUM of 'costs' for every year + all the years before it?

我有两个名为 wh_timewh_fact 的表,其中 wh_time 包括 time_idyear_id 两列,而 wh_fact 包括这两列列 time_idcost。 我尝试使用 rollup 函数来获取每年的成本与之前几年的成本的总和 .. 例如:

对于 2002 年,我想要(2002 年的成本 = 2000、2001 和 2002 年所有成本的总和)

我尝试了这个,但它不起作用..任何帮助!

SELECT year_id, SUM(cost) 
      FROM wh_fact f
      INNER JOIN wh_time t ON t.time_id = f.time_id  
GROUP BY ROLLUP (year_id, cost)
ORDER BY year_id
;

您可以使用解析函数来执行本质上是 运行 求和的操作:

select year_id,
       sum_cost as cost_this_yr,
       sum(sum_cost) over( order by year_id
                           rows between unbounded preceding
                            and current row ) as run_sum
  from (select year_id, sum(cost) as sum_cost
          from wh_fact
          join wh_time
         using (time_id)
         group by year_id)
 order by year_id

Fiddle: http://sqlfiddle.com/#!4/c0f27/3/0

| YEAR_ID | COST_THIS_YR | RUN_SUM |
|---------|--------------|---------|
|    2000 |          500 |     500 |
|    2001 |          400 |     900 |
|    2002 |          300 |    1200 |
|    2003 |          100 |    1300 |

(如果您不需要 cost_this_yr 列,只需将其从 select 列表中删除即可)