2014-01-29 60 views
-1

我困在未知狀態。我有一個如下面的#temp表。 使用SQL Server 2008 R2如何將列標題轉換爲貸款行的行

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

SELECT * FROM #TEMP

由上表僅有一行,我想三行如下

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

問題要求代碼必須展示出解決問題的最小的理解。告訴我們你試過的東西。 – Kermit

回答

2

您應該能夠使用以下與UNPIVOT功能:

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

請參閱SQL Fiddle with Demo

還是因爲你使用的是SQL Server 2008 R2中,這也可以使用CROSS APPLY寫:

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

SQL Fiddle with Demo