0

I'm working on TSQL stored procedure and I need to transform temporary table columns into rows. Currently I'm using updating table one by one but I think using pivot and unpivot this could be achieved this easily.

Data Source:

Periods      Stat1       Stat2       Stat3      Stat4
--------------------------------------------------------
Value1       1.011       1.012       1.013       1.014
Value2       1.011       1.021       1.031       1.041
Value3       1.011       2.211       1.311       1.411

Expected Output:

Stats        Value1       Value2       Value3
-----------------------------------------------
Stat1         1.011       1.011       1.011      
Stat2         1.012       1.021       1.211 
Stat3         1.013       1.031       1.311 
Stat4         1.014       1.041       1.411 

Really appreciate any help on this ?

2

1 Answer 1

1

As you've indicated it's a process of unpivoting then pivoting the data:

with statTable as
(
select periods = 'Value1', Stat1 = 1.011, Stat2 = 1.012, Stat3 = 1.013, Stat4 = 1.014
union all select 'Value2', 1.011, 1.021, 1.031, 1.041
union all select 'Value3', 1.011, 2.211, 1.311, 1.411
)
, up as
(
  select periods,
    c.[Stats], 
    c.value
  from statTable
  cross apply
  (
    values ('Stat1', Stat1), ('Stat2', Stat2), ('Stat3', Stat3), ('Stat4', Stat4)
  ) c ([Stats], value)
)
select [Stats],
  Value1,
  Value2,
  Value3
from up
pivot
(
  sum(value)
  for periods in (Value1, Value2, Value3)
) p

SQL Fiddle with demo.

If you're not using SQL Server 2008 or above, you can use UNPIVOT instead of CROSS APPLY:

with statTable as
(
select periods = 'Value1', Stat1 = 1.011, Stat2 = 1.012, Stat3 = 1.013, Stat4 = 1.014
union all select 'Value2', 1.011, 1.021, 1.031, 1.041
union all select 'Value3', 1.011, 2.211, 1.311, 1.411
)
, up as
(
  select periods,
    up.[Stats], 
    up.value
  from statTable
  unpivot
  (
    value
    for [Stats] in (Stat1, Stat2, Stat3, Stat4)
  ) up
)
select [Stats],
  Value1,
  Value2,
  Value3
from up
pivot
(
  sum(value)
  for periods in (Value1, Value2, Value3)
) p

SQL Fiddle with demo.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ian. Seems this should work for my problem. I'll check.

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.