How to convert Column header to Row for loannumber [closed]

倾然丶 夕夏残阳落幕 提交于 2019-12-20 07:46:14

问题


I am stuck in unpivoting. I have a table like #temp below. Using sql server 2008 r2

Select LoanNumber = 2000424385
    ,[AmntType1] = 120.32
    ,[AmntType2] = 131.52
    ,[AmntType3] = 142.36
    into #temp

select * from #temp

Above table has only one row and i want three rows as below

LoanNumber Amount AmountType
2000424385 120.32 AmntType1
2000424385 131.52 AmntType2
2000424385 120.32 AmntType1

回答1:


You should be able to use the following with the UNPIVOT function:

select loanNumber,
  amount, 
  amounttype
from #temp
unpivot
(
  amount
  for amounttype in (AmntType1, AmntType2, AmntType3)
) unp;

See SQL Fiddle with Demo.

Or because you are using SQL Server 2008 R2, this can also be written using CROSS APPLY:

select loannumber, 
  amount,
  amounttype
from #temp
cross apply
(
  values
    ('AmntType1', AmntType1),
    ('AmntType2', AmntType2),
    ('AmntType3', AmntType3)
) c (amounttype, amount);

See SQL Fiddle with Demo



来源:https://stackoverflow.com/questions/21439733/how-to-convert-column-header-to-row-for-loannumber

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!