将Sql查询结果从行转换为列名,其他行作为列数据

时间:2013-04-18 07:43:44

标签: sql-server tsql

我使用此查询来获得结果:

Declare @Mag Int = 237006
;With Res
As
(
  Select
    Mnf.FileTypeID As MagType,
    Mnf.InsertDate As MagDate,
    Mnf.Star,
    Nl.LogType,
    Nl.InsertDate As LogDate
  From 
    MagazineNumberFiles As Mnf
    Left Outer Join Nomags_Log As Nl On Nl.MagazineNumberID = Mnf.MagazineNumberID
  Where 
    Mnf.MagazineNumberID = @Mag
)
Select * From Res

此查询的结果是:

MagType MagDate         Star    LogType LogDate
2           2013-04-13  *       7       2013-04-16 
6           2013-04-14  *       3       2013-04-17 
8           2013-04-15  NULL    NULL    NULL

我想将此结果转换为:

MagType2    MagStar2 MagType6   MagStar6 MagType8 MagStar8 LogType7     LogType3
2013-04-13  *        2013-04-14 *        5        NULL     2013-04-16   2013-04-17

如何使用tsql执行此操作?

1 个答案:

答案 0 :(得分:1)

你可以用一些丑陋的动态sql:

declare @sql nvarchar(max) = '';

select @sql = 'select ' + stuff((select
',''' + convert(varchar,MagDate) + ''' as MagType' + convert(varchar,MagType)
+ char(10)
+ isnull(',''' + convert(varchar,Star) + '''', ',null') + ' as MagStar' 
+ convert(varchar,MagType)
+ char(10)
+ isnull(',''' + convert(varchar,LogDate) + ''' as LogType', '') 
+ isnull(convert(varchar,LogType), '')
+ char(10)
from Res
for xml path(''))
,1,1,'');

exec sp_executesql @sql;