将数据

按月统计变为

用游标实现代码如下:

Code
1
2
use AdventureWorks
3
select count(1) as CountRow,
4
ProductID,
5
sum(OrderQty) as Qty,
6
year(ModifiedDate) as TotalYear,
7
Month(ModifiedDate) as TotalMonth
8
into #Sales
9
from Sales.SalesOrderDetail
10
where year(ModifiedDate)=2001
11
group by ProductID,year(ModifiedDate),Month(ModifiedDate)
12
order by year(ModifiedDate),Month(ModifiedDate),productID
13
14
create table #Temp_GetReportRegion
15
(
16
ProductID int,
17
Jan int,
18
Feb int,
19
Mar int,
20
Api int,
21
May int,
22
Jun int,
23
Jul int,
24
Aug int,
25
Sep int,
26
Oct int,
27
Nov int,
28
Dec int
29
)
30
31
declare @Jan int
32
declare @Feb int
33
declare @Mar int
34
declare @Api int
35
declare @May int
36
declare @Jun int
37
declare @Jul int
38
declare @Aug int
39
declare @Sep int
40
declare @Oct int
41
declare @Nov int
42
declare @Dec int
43
44
set @Jan = 0
45
set @Feb = 0
46
set @Mar = 0
47
set @Api = 0
48
set @May = 0
49
set @Jun = 0
50
set @Jul = 0
51
set @Aug = 0
52
set @Sep = 0
53
set @Oct = 0
54
set @Nov = 0
55
set @Dec = 0
56
57
58
59
--声明一个游标
60
DECLARE MyCURSOR CURSOR FOR
61
SELECT ProductID,Qty,TotalYear,TotalMonth FROM #Sales
62
63
--打开游标
64
open MyCURSOR
65
66
--声明变量
67
declare @ProductID int
68
declare @Qty int
69
declare @TotalYear int
70
declare @TotalMonth int
71
72
--循环移动
73
fetch next from MyCURSOR into @ProductID,@Qty,@TotalYear,@TotalMonth
74
while(@@fetch_status=0)
75
begin
76
if @TotalMonth=1
77
set @Jan = @Jan+@Qty
78
else if @TotalMonth=2
79
set @Feb = @Feb+@Qty
80
else if @TotalMonth=3
81
set @Mar = @Mar+@Qty
82
else if @TotalMonth=4
83
set @Api = @Api+@Qty
84
else if @TotalMonth=5
85
set @May = @May+@Qty
86
else if @TotalMonth=6
87
set @Jun = @Jun+@Qty
88
else if @TotalMonth=7
89
set @Jul = @Jul+@Qty
90
else if @TotalMonth=8
91
set @Aug = @Aug+@Qty
92
else if @TotalMonth=9
93
set @Sep = @Sep+@Qty
94
else if @TotalMonth=10
95
set @Oct = @Oct+@Qty
96
else if @TotalMonth=11
97
set @Nov = @Nov+@Qty
98
else if @TotalMonth=12
99
set @Dec = @Dec+@Qty
100
fetch next from MyCURSOR into @ProductID,@Qty,@TotalYear,@TotalMonth
101
end
102
103
close MyCURSOR
104
deallocate MyCURSOR
105
insert into #Temp_GetReportRegion values(1,@Jan,@Feb,@Mar,@Api,@May,@Jun,@Jul,@Aug,@Sep,@Oct,@Nov,@Dec)
106
select * from #Temp_GetReportRegion