这种类型的数据转换是一个枢纽。有几种方法可以旋转数据。
聚合案例:这使用case
表达式和聚合函数来创建列
select
max(case when letter = 'b' then number end) B,
max(case when letter = 'i' then number end) I,
max(case when letter = 'n' then number end) N,
max(case when letter = 'g' then number end) G,
max(case when letter = 'o' then number end) O
from
(
select left(number, 1) letter,
number,
row_number() over(partition by left(number, 1)
order by cast(substring(number, 2, 2) as int)) rn
from yourtable
) src
group by rn
order by rn
请参阅带有演示的 SQL Fiddle
枢:
或者由于您使用的是 SQL Server 2005+,您可以使用以下PIVOT
功能:
select b, i, n, g, o
from
(
select left(number, 1) letter,
number,
row_number() over(partition by left(number, 1)
order by cast(substring(number, 2, 2) as int)) rn
from yourtable
) src
pivot
(
max(number)
for letter in (b, i, n, g, o)
) piv
请参阅带有演示的 SQL Fiddle