行列转换之——多行转多列,多列转多行实践版

 


行列转换之——多行转多列,多列转多行实践版

参考:深入行列转换----多行转多列,多行的计算

参考:sql server动态行列转换

 

1、多列转行(核心思想,利用row_number() over() 来构造列传行之后的唯一列,来行转列)

   要求:

   

 实操演示:

复制代码
select 'a' as 'a','b' as 'b','c' as 'c'
into #temp1
union all
select 'aa','bb','cc'
union all 
select 'aaa','bbb','ccc'

select * from 
(
    select column1,value,row_number() over(partition by column1 order by value) as rn from #temp1
    unpivot(value for column1 in(a,b,c) ) t
) a
pivot(max(value) for rn in ([1],[2],[3])) t1

 

复制代码

 

 

2、行转多列(核心row_number())

 

复制代码
select 'a' as 'a','b' as 'b','c' as 'c'
into #temp2
union all
select 'a' as 'a','b1' as 'b','c1' as 'c'
union all
select 'aa','bb','cc'
union all 
select 'aa','bb1','cc1'
union all
select 'aaa','bbb','ccc'
select * from #temp2
--1.全表
select * from #temp2
--2.构造row_number()
    select *,row_number() over(partition by a order by a) as 'rn' from  #temp2
--3.行转列
select a, max(case when rn = 1 then A else null end) [B_1],max(case when rn = 1 then B else null end) [C_1],
max(case when rn = 2 then A else null end) [B_2],max(case when rn = 2 then B else null end) [C_2]
from 
(
    select *,row_number() over(partition by a order by a) as 'rn' from  #temp2
) a
GROUP BY A


 



复制代码

 

3.直接行转列

  

复制代码
select 'a' as [c1],1 as 'c2'
union all
select 'b' as [c1],2 as 'c2'

;with temp1 as (
select 'a' as [c1],1 as 'c2'
union all
select 'b' as [c1],2 as 'c2'
)
select 
max(case when rn=1 then c1 else null end) as [c1_1],
max(case when rn=1 then c2 else null end) as [c2_1], max(case when rn=2 then c1 else null end) as [c1_1],
max(case when rn=2 then c2 else null end) as [c2_1] from (select *,row_number() over(order by c1) as [rn] from temp1) t

 


复制代码

 

posted @   郭大侠1  阅读(4621)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示