4

我有很多客户,每个客户都有 67 条记录。

该记录包含活动、日期、ID、标志和许多其他列。

我希望活动名称成为这些活动标题下方的标题和日期。

我正在尝试使用下表进行更多解释。这是当前的输出:

Client  Activity    Date 
1       A           21/15
1       B           5/5/2012
1       C           51/3115
1       D           54/6/84
2       A           8/6/99
2       B           1/1/2011
2       C           8/4
2       D           9/81/1
3       A           6/51/8
3       B           1/61/8
3       C           1/31
3       D           3/2/1

我希望它是:

Client      A       B         C         D
1           21/15   5/5/2012  51/31/15  54/6/84
2           8/6/99  1/1/2011  8/4       9/81/1
3           6/51/8  1/61/8    1/31      3/2/1
4

1 回答 1

4

您将需要为此使用该PIVOT功能。如果您知道要转换的列数,则可以通过静态数据透视对其进行硬编码:

select *
from
(
  select client, activity, dt
  from yourtable
) x
pivot
(
  max(dt)
  for activity in ([A], [B], [C], [D])
) p

SQL Fiddle with Demo

如果您的列数未知,请使用动态版本:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(activity) 
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT client,' + @cols + ' from 
             (
              select client, activity, dt
              from yourtable
            ) x
            pivot 
            (
                max(dt)
                for activity in (' + @cols + ')
            ) p '

execute(@query)

SQL Fiddle with Demo

最后,这也可以通过CASE语句和聚合函数来完成(参见SQL Fiddle with Demo):

select client,
  max(case when activity = 'A' then dt end) as A,
  max(case when activity = 'B' then dt end) as B,
  max(case when activity = 'C' then dt end) as C,
  max(case when activity = 'D' then dt end) as D
from yourtable
group by client
于 2012-09-20T16:05:25.137 回答