最近在SQLSERVER中需要计算YTD的数据,以前使用oracle时粗略使用过分析函数(窗口函数),所以当时还以为很简单,一两个语句就完成。
源表(例子):
日期 | 金额 |
1 | 50 |
2 | 20 |
3 | 40 |
4 | 60 |
希望得到的数据:
日期 | 金额 | 累积金额 |
1 | 50 | 50 |
2 | 20 | 70 |
3 | 40 | 110 |
4 | 60 | 170 |
然而当我从容地敲下这句代码:
select 日期,金额,sum(金额) as 累积金额 over(order by 日期) from 源表
却出现这样的错误:
Msg 11305, Level 15, State 10, Line 21 The Parallel Data Warehouse (PDW) features are not enabled.
百度过后才发现,分析函数中涉及汇总的计算在2012版本后才能使用。
无奈之下,只好使用游标一天一天地慢慢累积起来计算。
创建临时表
1 create table #source_table 2 ( 3 date int, 4 money int 5 ) 6 7 create table #target_table 8 ( 9 date int, 10 money int, 11 money_ytd int 12 )
插入数据
1 insert into #source_table values(1,50) 2 insert into #source_table values(2,20) 3 insert into #source_table values(3,40) 4 insert into #source_table values(4,60)
声明变量
1 declare 2 @date_cursor CURSOR, 3 @date int, 4 @money_ytd int
参数设置
set @money_ytd=0 set @date_cursor=CURSOR LOCAL forselect distinct date from #source_table order by date
打开游标
Open @date_cursor fetch next from @date_cursor into @date
代码主体 --@@FETCH_STATUS=0时,游标顺利移动到下一行,否则表示当前已经到游标末尾,无法下移。
1 while (@@FETCH_STATUS=0) 2 begin 3 4 select @money_ytd=@money_ytd+money from #source_table where date=@date 5 6 insert into #target_table 7 select 8 date, 9 money, 10 @money_ytd 11 from #source_table where date=@date 12 13 fetch next from @date_cursor into @date 14 end
关闭游标
close @date_cursor
释放游标
deallocate @date_cursor
检查输出结果
select * from #target_table
第一篇技术博客,其实并非为了分享,是为了以下几点:
1.记录自己工作中遇到的问题及解决方案。
2.写作中可以发现自己以前是懂非懂的部分。(这次就发现了@@FETCH_STATUS)
3.作为一个开始,启程是通往后续路程的前提条件。(想起数学归纳法,总得找到一个满足证明要求的初始条件,那就是一切的起步。)