用聚合函数配合CASE语句实现行转列功能:
现在分享一下具体实现代码:
转换前效果:
PlanName | PlanType | PlanLimit |
计划1 | 计划类型1 | RMB 1,000,000 |
计划1 | 计划类型2 | RMB 1,000,000 |
计划1 | 计划类型3 | RMB 1,000,000 |
计划2 | 计划类型1 | RMB 1,000,000 |
计划2 | 计划类型2 | RMB 1,000,000 |
计划2 | 计划类型3 | RMB 1,000,000 |
计划3 | 计划类型1 | RMB 1,000,000 |
计划3 | 计划类型2 | RMB 1,000,000 |
计划3 | 计划类型3 | RMB 1,000,000 |
1、静态实现行转列
with main as
(
select '计划1' as PlanName,'计划类型1' as PlanType,'RMB 1,000,000' as PlanLimit
union all
select '计划1' as PlanName,'计划类型2' as PlanType,'RMB 1,000,000' as PlanLimit
union all
select '计划1' as PlanName,'计划类型3' as PlanType,'RMB 1,000,000' as PlanLimit
union all
select '计划2' as PlanName,'计划类型1' as PlanType,'RMB 1,000,000' as PlanLimit
union all
select '计划2' as PlanName,'计划类型2' as PlanType,'RMB 1,000,000' as PlanLimit
union all
select '计划2' as PlanName,'计划类型3' as PlanType,'RMB 1,000,000' as PlanLimit
union all
select '计划3' as PlanName,'计划类型1' as PlanType,'RMB 1,000,000' as PlanLimit
union all
select '计划3' as PlanName,'计划类型2' as PlanType,'RMB 1,000,000' as PlanLimit
union all
select '计划3' as PlanName,'计划类型3' as PlanType,'RMB 1,000,000' as PlanLimit
)
select PlanType as [计划]
,'计划1'=max(case PlanName when '计划1' then PlanLimit else null end)
,'计划2'=max(case PlanName when '计划2' then PlanLimit else null end)
,'计划3'=max(case PlanName when '计划3' then PlanLimit else null end)
from main
where =
group by PlanType
2、动态实现行转列
-- =============================================
-- Author: <Anne>
-- Create date: <//>
-- Description: <查询SP_AnneTest表的数据>
-- =============================================
CREATE PROCEDURE [dbo].[SP_AnneTest]
(
)
AS
declare @sql varchar()
BEGIN
set @sql='' select @sql=@sql+','+''''+[PlanName]+''''+'=max(case PlanName when '''+[PlanName]+''' then PlanLimit else null end)'
from main
where =
group by PlanType
set @sql='select PlanType as [''计划'']'+@sql+'
from main
where =
group by PlanType' print @sql
exec(@sql) END
GO
实现效果:
计划 | 计划1 | 计划2 | 计划3 |
计划类型1 | RMB 1,000,000 | RMB 1,000,000 | RMB 1,000,000 |
计划类型2 | RMB 1,000,000 | RMB 1,000,000 | RMB 1,000,000 |
计划类型3 | RMB 1,000,000 | RMB 1,000,000 | RMB 1,000,000 |