[SQL Server]SQL行转列

SELECT * FROM (
select ActionTargetType+actiontype as TypeResult, COUNT(RowGuid) as Number from BanJianLogInfo group by ActionTargetType,actiontype
union
select ActionTargetType+OperateResult+'总数' as TypeResult,count(*) from BanJianLogInfo
group by ActionTargetType,OperateResult
union
select ActionTargetType+'总数' as TypeResult,count(*) from BanJianLogInfo group by ActionTargetType
)temp
PIVOT
( sum(Number) /*行转列后 列的值*/ FOR
temp.TypeResult/*需要行转列的列*/ IN ([办件信息成功总数],[办件信息更新],[办件信息失败总数],[办件信息新增]/*列的值*/)
) AS T
转换前

转换后

语法:

SELECT * FROM TableName temp /*需要行转列数据源*/
PIVOT
( sum(ColumnName1) /*行转列后 列的值*/ FOR
temp.ColumnName2/*需要行转列的列*/ IN ([办件信息成功总数],[办件信息更新],[办件信息失败总数],[办件信息新增]/*列的值*/)
) AS T

posted @ 2018-06-21 09:31  阿婆说  阅读(390)  评论(0编辑  收藏  举报