2

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

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 做到这一点?

4

1 回答 1

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;
于 2013-04-18T11:51:33.973 回答