由于您将返回未知数量的行,因此您需要实现动态 SQL 来获取结果。您还需要对 3 列进行反透视,然后应用 PIVOT 将行转换回列,因此这将是一个两步过程。
由于您关心使用 SQL Server 2005+,因此您可以使用 CROSS APPLY 来取消透视数据,您会注意到我也使用row_number()
了这样,因此当返回到列时,数据行仍然分组在一起。UNPIVOT 数据的代码将类似于:
select col+'_'+cast(rn as varchar(50)) col,
value
from
(
select [set] as st, cost, times,
row_number() over(order by (select 1)) rn
from yourtable
) d
cross apply
(
values
('set', st),
('cost', cast(cost as varchar(50))),
('times', cast(times as varchar(50)))
) c (col, value);
请参阅演示。这会将数据转换为以下格式:
| COL | VALUE |
-------------------
| set_1 | GHT |
| cost_1 | 100 |
| times_1 | 20 |
一旦数据位于多行中,您就可以应用 PIVOT。动态 SQL 代码将类似于以下内容:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(col+'_'+cast(rn as varchar(50)))
from
(
select row_number() over(order by (select 1)) rn
from yourtable
) d
cross apply
(
select 'set', 1 union all
select 'cost', 2 union all
select 'times', 3
) c (col, so)
group by col, rn, so
order by rn, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + '
from
(
select col+''_''+cast(rn as varchar(50)) col,
value
from
(
select [set], cost, times,
row_number() over(order by (select 1)) rn
from yourtable
) d
cross apply
(
values
(''set'', [set]),
(''cost'', cast(cost as varchar(50))),
(''times'', cast(times as varchar(50)))
) c (col, value)
) x
pivot
(
max(value)
for col in (' + @cols + ')
) p '
execute(@query);
请参阅SQL Fiddle with Demo。这给出了一个结果:
| SET_1 | COST_1 | TIMES_1 | SET_2 | COST_2 | TIMES_2 | SET_3 | COST_3 | TIMES_3 |
----------------------------------------------------------------------------------
| GHT | 100 | 20 | GHA | 80 | 30 | GHE | 70 | 10 |