0
A_first B_first C_first  A_second  B_second  C_second A_third  B_third  C_third
638      450     188       638       439       187      546      256      789

我有一张这样的桌子,只有一排。我怎样才能旋转这一行,以便我得到每个, ,A B C的列和一行?_first_second_third

我正试图围绕 sql 中的 pivot/unpivot 命令

A          B      C     
638      450     188     
638      439     187     
546      256     789

使用 SQL Server 2008,所以我有 pivot/unpivot 命令。更具体地说,SSMS 告诉我我连接到的数据库是9.0 SP3

4

1 回答 1

1

您没有指定您使用的 RDBMS,所以这里有两个解决方案。如果你有一个UNPIVOT函数,然后是一个PIVOT

select *
from
(
  select value, left(fields, 1) col,
    substring(fields, 3, len(fields) -2) row
  from yourtable
  unpivot
  (
    value
    for fields in(A_first, B_first, C_first,
                  A_second, B_second, C_second,
                  A_third, B_third, C_third)
  ) unpiv
) src
pivot
(
  max(value)
  for col in ([A], [B], [C])
) piv

请参阅带有演示的 SQL Fiddle

如果您没有UNPIVOTandPIVOT功能,那么您可以使用UNION ALL

select
  max(case when col = 'A' then value end) A,
  max(case when col = 'B' then value end) B,
  max(case when col = 'C' then value end) C
from
(
  select value, left(fields, 1) col, substring(fields, 3, len(fields) -2) row
  from
  (
    select A_first value, 'A_first' fields
    from yourtable
    union all
    select B_first value, 'B_first' fields
    from yourtable
    union all
    select C_first value, 'C_first' fields
    from yourtable
    union all
    select A_second value, 'A_second' fields
    from yourtable
    union all
    select B_second value, 'B_second' fields
    from yourtable
    union all
    select C_second value, 'C_second' fields
    from yourtable
    union all
    select A_third value, 'A_third' fields
    from yourtable
    union all
    select B_third value, 'B_third' fields
    from yourtable
    union all
    select C_third value, 'C_third' fields
    from yourtable
  ) unpiv
) src
group by row

请参阅带有演示的 SQL Fiddle

两者都会产生相同的结果:

|   A |   B |   C |
-------------------
| 638 | 450 | 188 |
| 638 | 439 | 187 |
| 546 | 256 | 789 |

请注意,为了执行此任务,每列的数据类型必须相同。如果它们不是,那么您将需要convertUNPIVOT.

这个答案做了一些假设:

  1. 现有列将始终以新列值开头(ABC等)
  2. 现有列将始终以行号前的两个字符开头。
于 2012-11-21T16:37:13.513 回答