行列转换之 您所在的位置:网站首页 Pg行转列 行列转换之

行列转换之

2024-07-16 08:01| 来源: 网络整理| 查看: 265

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

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

参考: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

 

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有