假设我有类似这样的1D表:
TBL_1
[ Task ][ Entity ][ Timespan ]
[ TASK1 ][ ID1 ][ 3 ]
[ TASK2 ][ ID2 ][ 4 ]
[ TASK2 ][ ID1 ][ 5 ]
[ TASK1 ][ ID2 ][ 6 ]
如何将其转换为类似2D的视图:
[ Entity ][ TASK1 ][ TASK2 ]
[ ID1 ][ 3 ][ 5 ]
[ ID2 ][ 6 ][ 4 ]
鉴于任务数量应该是动态的吗?
我目前的解决方案如下:
SELECT A.Entity, B.Task TASK1, C.Task TASK2
FROM (SELECT DISTINCT ENTITY FROM TBL_1) A
LEFT JOIN TBL_1 B
ON A.Entity = B.Entity AND B.Task = 'TASK1'
LEFT JOIN TBL_1 C
ON A.Entity = C.Entity AND C.Task = 'TASK2'
但这要求我“硬编码”任务。我怎么能让这种动态变化?
非常感谢!
答案 0 :(得分:3)
您正在寻找PIVOT
。您可以使用动态SQL数据透视表。这种策略将使列名在执行查询时转换:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(task)
from t1
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT entity, ' + @cols + ' from
(
select entity, task, timespan
from t1
) x
pivot
(
min(timespan)
for task in (' + @cols + ')
) p '
execute(@query)
答案 1 :(得分:0)
你也可以本着你所尝试的精神去做。但是,使用group by比你尝试的更简单:
SELECT ENTITY,
max(case when t.task = 'Task1' then timespan end) as task1,
max(case when t.task = 'Task2' then timespan end) as task2,
. . .
FROM TBL_1 t
group by entity
要动态生成列,您需要使用动态SQL。这是你真正想要的吗?