列转行

  1. --方法1:使用pivot
  2. CREATE table #yourtable
  3. ([Id] int, [Value] varchar(6), [ColumnName] varchar(13))
  4. ;
  5. INSERT INTO #yourtable
  6. ([Id], [Value], [ColumnName])
  7. VALUES
  8. (1, 'John', 'FirstName'),
  9. (2, '2.4', 'Amount'),
  10. (3, 'ZH1E4A', 'PostalCode'),
  11. (4, 'Fork', 'LastName'),
  12. (5, '857685', 'AccountNumber')
  13. ;
  14. select *
  15. from
  16. (
  17. select value, columnname
  18. from #yourtable
  19. ) d
  20. pivot
  21. (
  22. max(value)
  23. for columnname in (Firstname, Amount, PostalCode, LastName)
  24. ) piv;
  25. --方法2:使用left join
  26. select fn.value as FirstName,
  27. a.value as Amount,
  28. pc.value as PostalCode,
  29. ln.value as LastName,
  30. an.value as AccountNumber
  31. from yourtable fn
  32. left join yourtable a
  33. on fn.somecol = a.somecol
  34. and a.columnname = 'Amount'
  35. left join yourtable pc
  36. on fn.somecol = pc.somecol
  37. and pc.columnname = 'PostalCode'
  38. left join yourtable ln
  39. on fn.somecol = ln.somecol
  40. and ln.columnname = 'LastName'
  41. left join yourtable an
  42. on fn.somecol = an.somecol
  43. and an.columnname = 'AccountNumber'
  44. where fn.columnname = 'Firstname'

参考

Efficiently convert rows to columns in sql server