将sql中的两列拆分为多列

时间:2021-03-25 04:24:45

I have data in following format

我有以下格式的数据

 ID      Loss        Sum
--------------------------
 1     146276293.1    1
 1     175538865.5    2
 1     146276293.1    3 

I want SQL script to return me

我希望SQL脚本能够归还给我

   ID      Sum1         Sum2         Sum3
   --------------------------------------------------- 
   1     146276293.1  175538865.5   146276293.1    

1 个解决方案

#1


1  

This simple example does what you're trying to do. PIVOT is a great tool. Also research UNPIVOT when attempting the opposite.

这个简单的例子就是你要做的。 PIVOT是一个很棒的工具。在尝试相反时也研究UNPIVOT。

select *
from (  
        select 1 id, 100 num, 'Sum1' col
        union select 1, 200, 'Sum2'
        union select 1, 300, 'Sum3' ) x
pivot 
(sum(num) for col in (Sum1, Sum2, Sum3)) p

#1


1  

This simple example does what you're trying to do. PIVOT is a great tool. Also research UNPIVOT when attempting the opposite.

这个简单的例子就是你要做的。 PIVOT是一个很棒的工具。在尝试相反时也研究UNPIVOT。

select *
from (  
        select 1 id, 100 num, 'Sum1' col
        union select 1, 200, 'Sum2'
        union select 1, 300, 'Sum3' ) x
pivot 
(sum(num) for col in (Sum1, Sum2, Sum3)) p