是否可以使用存储过程或视图将当前表转换为目标视图,此处ID是唯一的,每个ID可能包含不同类型的帐户,每种类型可以包含多个数字。 有人可以帮忙吗?
当前表格
ID Type Account Balance
1 checking 11111 100
1 checking 22222 200
1 savings 33333 300
1 savings 4444 400
2 investment 55555 500
2 checking 66666 600
目标
ID Key Value
1 Checking1_Account 11111
1 Checking2_Account 22222
1 Checking1_Balance 100
1 Checking2_Balance 200
1 Savings1_Account 33333
1 Savings2_Account 44444
1 Savings1_Balance 300
1 Savings2_Balance 400
2 Investment1_Account 55555
2 Investment1_Balance 500
2 Checking1_Account 66666
2 Checking1_Balance 600
答案 0 :(得分:2)
示例强>
;with cte as (
Select *,RN = Row_Number() over (Partition By ID,Type Order by Account)
From YourTable
)
Select A.ID
,B.*
From cte A
Cross Apply (values (concat(A.[Type],A.RN,'_Account'),A.Account)
,(concat(A.[Type],A.RN,'_Balance'),A.Balance)
) B ([Key],Value)
<强>返回强>
EDIT 2008兼容
;with cte as (
Select *,RN = Row_Number() over (Partition By ID,Type Order by Account)
From YourTable
)
Select A.ID
,B.*
From cte A
Cross Apply (values (A.[Type]+cast(A.RN as varchar(25))+'_Account',A.Account)
,(A.[Type]+cast(A.RN as varchar(25))+'_Balance',A.Balance)
) B ([Key],Value)
答案 1 :(得分:1)
for sql-server 2008
select *
into #tempt
from
(values (1, 'checking', '11111', 100),
(1, 'checking', 22222, 200),
(1, 'savings', 33333 , 300),
(1, 'savings', 4444 , 400),
(2, 'investment', 55555 , 500),
(2, 'checking', 66666 , 600)
) x (ID, Type, Account, Balance)
select ID,Type + cast(row_number() over (partition by ID,Type Order by Account) as varchar(5)) + '_Account' [Key],Account [Value] from #tempt
union
select ID,Type + cast(row_number() over (partition by ID,Type Order by Account) as varchar(5)) + '_Balance' [Key],Account [Value] from #tempt order by id, [key]
drop table #tempt
(6 row(s) affected)
ID Key Value
----------- ------------------------------------------ -----------
1 checking1_Account 11111
1 checking1_Balance 100
1 checking2_Account 22222
1 checking2_Balance 200
1 savings1_Account 4444
1 savings1_Balance 400
1 savings2_Account 33333
1 savings2_Balance 300
2 checking1_Account 66666
2 checking1_Balance 600
2 investment1_Account 55555
2 investment1_Balance 500