欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[SQL Server]SQL行转列

程序员文章站 2022-06-29 17:28:32
SELECT * FROM (select ActionTargetType+actiontype as TypeResult, COUNT(RowGuid) as Number from BanJianLogInfo group by ActionTargetType,actiontype uni ......

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
转换前

[SQL Server]SQL行转列

转换后

[SQL Server]SQL行转列

语法:

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