我有很多客户,每个客户有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
答案 0 :(得分:4)
您需要使用PIVOT
功能。如果您知道要转换的列数,那么您可以通过静态数据透视表对其进行硬编码:
select *
from
(
select client, activity, dt
from yourtable
) x
pivot
(
max(dt)
for activity in ([A], [B], [C], [D])
) p
如果您的列数未知,请使用动态版本:
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)
最后,这也可以使用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