Sql-Server

SQL Server 2008 之間的行版本…前一行和目前行

  • November 28, 2018

作為一個初學者,我很難在 SQL Server 2008 中編寫這個特定場景

在此處輸入圖像描述

如您所見,例如 2017 年 7 月的 SUM 列等於以下內容:2016 年 8 月至 12 月 + 2017 年 1 月至 7 月 = 4625

同樣,2017 年 8 月的 SUM 列等於:2016 年 9 月至 12 月 + 2017 年 1 月至 8 月 = 4625

在此處輸入圖像描述

我怎樣才能每月自動執行此操作?

我知道這可以使用 SQL Server 2012 及更高版本中的視窗函式來完成,但我必須修改此查詢才能在 SQL Server 2008 中工作

select year(date), month(date),
  sum(sum(numbers)) over (order by year(date), month(date) rows between 11 preceding and current row) as prev_12_sum
from t
group by year(date), month(date)
order by min(date);

我很感激我能得到的任何幫助。

這是一種方法(不幸的是,它適用於 2012+ 版本):

with 
 cte as
 ( select
       year(date) as year,
       month(date) as month,
       sum(sum(numbers)) over (order by year(date), month(date))
           as running_total,
       row_number() over (order by year(date), month(date))
           as rn,
   from t
   group by year(date), month(date)
 )
select
   t.year, t.month,
   t.running_total - coalesce(p.runinng_total, 0)
       as total_12_months
from
   cte as t
   left join cte as p
   on t.rn - 12 = p.rn ;

這只有在沒有幾個月的間隙(沒有任何條目)時才有效。


另一個嘗試,對於舊版本:

with 
 cte as
 ( select
       year(date) as year,
       month(date) as month,
       sum(numbers) as sum_numbers
   from t
   group by year(date), month(date)
 )
select
   t.year, t.month,
   sum(p.sum_numbers) as total_12_months
from
   cte as t
   left join cte as p
   on p.year = t.year - 1 and p.month > t.month
   or p.year = t.year     and p.month <= t.month
group by
   t.year, t.month ;

引用自:https://dba.stackexchange.com/questions/223703