PIVOT 与 UNPIVOT
语法:
SELECT <非透视的列>,
[第一个透视的列] AS <列名称>,
[第二个透视的列] AS <列名称>,
...
[最后一个透视的列] AS <列名称>,
FROM
(<生成数据的 SELECT 查询>)
AS <源查询的别名>
PIVOT
(
<聚合函数>(<要聚合的列>)
FOR
[<包含要成为列标题的值的列>]
IN ( [第一个透视的列], [第二个透视的列],
... [最后一个透视的列])
) AS <透视表的别名>
<可选的 ORDER BY 子句>;
代码:
create table tb2(serial_no int,testname varchar(10))
insert into tb2
select 1,'普通' union all
select 1,'普通' union all
select 3,'项目' union all
select 2,'项目'
select * from (select * from tb2) tmp pivot(count(serial_no) for testname in(普通,项目)) td
我觉得是:
1、先执行pivot 以外列的 group by。 select s1,s2,s3... from tb2 group by s1,s2,s3...
select testname,count(serial_no) from tb2 group by testname ,如果没有其他列,直接是 上面的执行结果。
2、将 for in(普通,项目) 里面的in放到列里面,聚合函数的值当成值来显示
UNPIVOT
是相反,将列转为行
CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,
Emp3 int, Emp4 int, Emp5 int);
GO
INSERT INTO pvt VALUES (1,4,3,5,4,4);
INSERT INTO pvt VALUES (2,4,1,5,5,5);
INSERT INTO pvt VALUES (3,4,3,5,4,4);
INSERT INTO pvt VALUES (4,4,2,5,5,4);
INSERT INTO pvt VALUES (5,5,1,5,5,5);
GO
--Unpivot the table.
SELECT VendorID, Employee, Orders
FROM
(SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
FROM pvt) p
UNPIVOT
(Orders FOR Employee IN
(Emp1, Emp2, Emp3, Emp4, Emp5)
)AS unpvt;
GO
select * from pvt
UNPIVOT
(Orders FOR Employee IN
(Emp1, Emp2, Emp3, Emp4, Emp5)
)
Orders表示值,Employee表示列 转为行。。
select WFCode,
[安全事件审计],[稽核事件申告],[流程结束],[市稽核班稽核],[事件申告],[营业厅稽核]
from
(select * from WFInstance ) as p
pivot
(
count(CurrentStepName)
FOR CurrentStepName IN ([安全事件审计],[稽核事件申告],[流程结束],[市稽核班稽核],[事件申告],[营业厅稽核])
)
as pvt
参考
http://www.cnblogs.com/kerrycode/archive/2010/07/28/1786547.html
http://www.cnblogs.com/chinabc/archive/2009/12/15/1624913.html
http://technet.microsoft.com/zh-cn/library/ms177410.aspx
http://www.cnblogs.com/emanlee/archive/2009/08/14/1546353.html
posted on 2011-03-12 22:56 jianshaohui 阅读(265) 评论(0) 编辑 收藏 举报