1

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

   ID      Sum1         Sum2         Sum3
   --------------------------------------------------- 
   1     146276293.1  175538865.5   146276293.1    
4
  • 1
    looks like you shouldl create a pivot select Commented Sep 10, 2015 at 17:32
  • Look into dynamic pivot. Commented Sep 10, 2015 at 17:32
  • Case statements or pivot would work if sum is limited to 3 groups if variable in number then dynamic pivot. Commented Sep 10, 2015 at 17:50
  • 1
    Instead of dynamic pivots I prefer to use a dynamic cross tab. The syntax is less obtuse to me. sqlservercentral.com/articles/Crosstab/65048 Commented Sep 10, 2015 at 18:06

1 Answer 1

1

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

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.