sql2005 行列转换

PIVOT和UNPIVOT关系运算符是SQL Server 2005提供的新增功能,因此,对升级到SQL Server 2005的数据库使用PIVOT和UNPIVOT时,数据库的兼容级别必须设置为90(可以使用sp_dbcmptlevel存储过程设置兼容级别)。

  在查询的FROM子句中使用PIVOT和UNPIVOT,可以对一个输入表值表达式执行某种操作,以获得另一种形式的表。PIVOT运算符将输入表的行旋转为列,并能同时对行执行聚合运算。而UNPIVOT运算符则执行与PIVOT运算符相反的操作,它将输入表的列旋转为行。

  在FROM子句中使用PIVOT和UNPIVOT关系运算符时的语法格式如下:

[ FROM { <table_source> } [ ,...n ] ]

<table_source> ::= {
 table_or_view_name [ [ AS ] table_alias ]
 <pivoted_table> | <unpivoted_table>
}

<pivoted_table> ::=table_source PIVOT <pivot_clause> table_alias

<pivot_clause> ::=( aggregate_function ( value_column )
 FOR pivot_column
  IN ( <column_list> )
)

<unpivoted_table> ::=table_source UNPIVOT <unpivot_clause> table_alias

<unpivot_clause> ::=( value_column FOR pivot_column IN ( <column_list> ) )

<column_list> ::= column_name [ , ... ] table_source PIVOT <pivot_clause>

  指定对table_source表中的pivot_column列进行透视。table_source可以是一个表、表表达式或子查询。

aggregate_function

  系统或用户定义的聚合函数。注意:不允许使用COUNT(*)系统聚合函数。

value_column

  PIVOT运算符用于进行计算的值列。与UNPIVOT一起使用时,value_column不能是输入table_source中的现有列的名称。

FOR pivot_column

  PIVOT运算符的透视列。pivot_column必须是可隐式或显式转换为nvarchar()的类型。

  使用UNPIVOT时,pivot_column是从table_source中提取输出的列名称,table_source中不能有该名称的现有列。

IN ( column_list )

  在PIVOT子句中,column_list列出pivot_column中将成为输出表的列名的值。

  在UNPIVOT子句中,column_list列出table_source中将被提取到单个pivot_column中的所有列名。

table_alias

  输出表的别名。

UNPIVOT < unpivot_clause >

  指定将输入表中由column_list指定的多个列的值缩减为名为pivot_column的单个列。

  常见的可能会用到PIVOT的情形是:需要生成交叉表格报表以汇总数据。交叉表是使用较为广泛的一种表格式,例如,图5-4所示的产品销售表就是一个典型的交叉表,其中的月份和产品种类都可以继续添加。但是,这种格式在进行数据表存储的时候却并不容易管理,要存储图5-4这样的表格数据,数据表通常需要设计为图5-5这样的结构。这样就带来一个问题,用户既希望数据容易管理,又希望能够生成一种能够容易阅读的表格数据。好在PIVOT为这种转换提供了便利

 

 

--08年注册用户按年龄段统计
select * from(
select datepart(month,iInputDate) as dates,count(0) as cc
from clubmemberinfo(nolock)
where iinputdate>='2008-01-01' and iInputDate<'2009-01-01'
and ibirthday>=dateadd(year,-45,getdate())
and ibirthday<dateadd(year,-40,getdate())
group by datepart(month,iInputDate)
) as tb
pivot (sum(cc) for dates in([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) as pvt

--08年注册用户按月收入统计
select * from(
select iincome,datepart(month,iInputDate) as dates,count(0) as cc
from clubmemberinfo(nolock)
where iInputDate >='2008-01-01' and iInputDate<'2009-01-01' and iincome is not null
group by iincome,datepart(month,iInputDate)
) as tb pivot (sum(cc) for dates in([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) as pvt

--08年注册用户性别按月统计
select * from (
select datepart(month,mregdate) as regmonth,count(0) as cc
from clubmember(nolock)
where mregdate >='2008-01-01' and mregdate<'2009-01-01' and msex>20
group by datepart(month,mregdate))as tb
PIVOT (sum(cc) for regmonth
in([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) as unpvt

posted @ 2009-06-23 20:15  xihongshibeibei  阅读(786)  评论(0编辑  收藏  举报