用游标实现行转列
将数据

按月统计变为
![]()
用游标实现代码如下:
1

2
use AdventureWorks3
select count(1) as CountRow,4
ProductID,5
sum(OrderQty) as Qty,6
year(ModifiedDate) as TotalYear,7
Month(ModifiedDate) as TotalMonth8
into #Sales9
from Sales.SalesOrderDetail10
where year(ModifiedDate)=200111
group by ProductID,year(ModifiedDate),Month(ModifiedDate)12
order by year(ModifiedDate),Month(ModifiedDate),productID13

14
create table #Temp_GetReportRegion15
(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 int29
)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 #Sales62
63
--打开游标64
open MyCURSOR65
66
--声明变量67
declare @ProductID int68
declare @Qty int69
declare @TotalYear int70
declare @TotalMonth int71
72
--循环移动73
fetch next from MyCURSOR into @ProductID,@Qty,@TotalYear,@TotalMonth74
while(@@fetch_status=0)75
begin76
if @TotalMonth=1 77
set @Jan = @Jan+@Qty78
else if @TotalMonth=2 79
set @Feb = @Feb+@Qty80
else if @TotalMonth=3 81
set @Mar = @Mar+@Qty82
else if @TotalMonth=4 83
set @Api = @Api+@Qty84
else if @TotalMonth=5 85
set @May = @May+@Qty86
else if @TotalMonth=6 87
set @Jun = @Jun+@Qty88
else if @TotalMonth=7 89
set @Jul = @Jul+@Qty90
else if @TotalMonth=8 91
set @Aug = @Aug+@Qty92
else if @TotalMonth=9 93
set @Sep = @Sep+@Qty94
else if @TotalMonth=10 95
set @Oct = @Oct+@Qty96
else if @TotalMonth=11 97
set @Nov = @Nov+@Qty98
else if @TotalMonth=12 99
set @Dec = @Dec+@Qty100
fetch next from MyCURSOR into @ProductID,@Qty,@TotalYear,@TotalMonth101
end102
103
close MyCURSOR104
deallocate MyCURSOR105
insert into #Temp_GetReportRegion values(1,@Jan,@Feb,@Mar,@Api,@May,@Jun,@Jul,@Aug,@Sep,@Oct,@Nov,@Dec)106
select * from #Temp_GetReportRegion
posted on 2009-06-12 10:55 zengshunyou 阅读(326) 评论(0) 收藏 举报
浙公网安备 33010602011771号