SQL2008中有两个函数:
- pivot
- unpivot
1.pivot可实现数据表的列转行
语法如下:
select * from table pivot( 聚合函数(<列名1>) for <列名2> in(<转换的行中列2的值1,转换的行中列2的值2,,...>))
例:
declare @temptable table([name] varchar(100),[saletype] varchar(100),[total] decimal(19,2))
insert into @temptable([name],[saletype],[total])
select '客户A','商品A','100'
union all
select '客户A','商品A','100'
union all
select '客户A','商品B','200'
union all
select '客户B','商品A','100'
union all
select '客户B','商品B','300'
union all
select '客户C','商品C','400'
select * from @temptable pivot(sum(total) for [saletype] in (商品A,商品B,商品C)) as pvt
这个方法,可以把某一列的值<列名1>求合后按照<列名2>转换到行上,行上的列名分别为in后面(列名2中的值)中的值,这个方法只能转换一列
2.unpivot可实现数据表的行转列语法如下:
select * from table unpivot(<转换后的值> for <转换后的列> in (<需要转换的列1,需要转换的列2,...>))
declare @temptable1 table([name] varchar(100),total1 decimal(19,2),total2 decimal(19,2),total3 decimal(19,2),total4 decimal(19,2))
insert into @temptable1
select 'A',1,2,3,4
union all
select 'B',11,22,33,44
select [name],[n],[v] from @temptable1
unpivot(v for n in(total1,total2,total3,total4)) a
注意:在in后面()中的值,是不允许重复的。
pivot函数只能把一列的值转到行上去,但现在有一个表如下
declare @temptable2 table([name] varchar(100),dateday varchar(20),qty decimal(19,2),total decimal(19,2))
insert into @temptable2
select 'A','1月1号',20,200
union all
select 'A','2月2号',10,100
union all
select 'A','3月3号',20,200
union all
select 'B','2月1号',10,100
union all
select 'B','1月1号',20,500
union all
select 'C','2月1号',10,100
union all
select 'C','2月2号',100,1000
现在一行有有两列,一个是qty,一个是total如果才能把这两列的转换到一行上去,现在用pivot好像不行,因为他只能转换一列,现在可以看一下上面的数据,应该按到dataday来转换,但又需要转换两个值。现在可以考虑先用unpivot函数先把行换成列,后再用pivot把列转成行。
select * from (
select [name],dateday + n as columname,v from @temptable2 unpivot(v for n in (qty,total)) a
) b pivot(sum(v) for [columname]
in ([1月1号qty],[1月1号total],[2月2号qty],[2月2号total],[3月3号qty],[3月3号total],
[2月1号qty],[2月1号total])) as c
这个地方还需要注意,有可能你的数据库没有设置兼容运用pivot和unpivot会报错,这个地方把SQL2008设置成
exec sp_dbcmptlevel DBName,100
DBName为对应的数据库名