列转行
--方法1:使用pivot
CREATE table #yourtable
([Id] int, [Value] varchar(6), [ColumnName] varchar(13))
;
INSERT INTO #yourtable
([Id], [Value], [ColumnName])
VALUES
(1, 'John', 'FirstName'),
(2, '2.4', 'Amount'),
(3, 'ZH1E4A', 'PostalCode'),
(4, 'Fork', 'LastName'),
(5, '857685', 'AccountNumber')
;
select *
from
(
select value, columnname
from #yourtable
) d
pivot
(
max(value)
for columnname in (Firstname, Amount, PostalCode, LastName)
) piv;
--方法2:使用left join
select fn.value as FirstName,
a.value as Amount,
pc.value as PostalCode,
ln.value as LastName,
an.value as AccountNumber
from yourtable fn
left join yourtable a
on fn.somecol = a.somecol
and a.columnname = 'Amount'
left join yourtable pc
on fn.somecol = pc.somecol
and pc.columnname = 'PostalCode'
left join yourtable ln
on fn.somecol = ln.somecol
and ln.columnname = 'LastName'
left join yourtable an
on fn.somecol = an.somecol
and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'
参考
Efficiently convert rows to columns in sql server