我想知道如何使用两列字符串在SQL表上执行数据透视,如下所示:
ID Label Text
---- ---------- ----------
10 Lead Source Internet
10 Display Washington
10 Sale Brick
10 Colour Blue
进入这个:
id Lead Source Display Sale Colour
-- ----------- ------- ---- ------
10 Internet Washington Brick Blue
答案 0 :(得分:1)
你可以使用枢轴功能来做到这一点。
SELECT *
FROM tablename
PIVOT ( Max([text])
FOR [label] IN ([Lead Source], [Display], [Sale], [Colour]) ) piv;
答案 1 :(得分:1)
如果您的label
有一些记录限制,那么您可以使用条件聚合:
select ID,
max(case when label = 'Lead Source' then text end) [Lead Source],
max(case when label = 'Display' then text end) [Display],
max(case when label = 'Sale' then text end) [Sale],
max(case when label = 'Colour' then text end) [Colour]
from table t
group by ID;
答案 2 :(得分:0)
示例数据
IF OBJECT_ID('tempdb..#t') iS NOT NULL
DROP TABLE #t
;With cte(ID, Label,[Text])
AS
(
SELECT 10,'Lead Source','Internet' UNION ALL
SELECT 10,'Display' ,'Washington' UNION ALL
SELECT 10,'Sale' ,'Brick' UNION ALL
SELECT 10,'Colour' ,'Blue'
)
SELECT ID, Label,[Text]
INTO #t FROM cte
使用Dynamic Sql
DECLARE @DyColumn Nvarchar(max),
@Sql Nvarchar(max)
SELECT @DyColumn=STUFF((SELECT DISTINCT ', '+QUOTENAME(Label) FROM #t ORDER BY 1 desc FOR XML PATH ('')),1,1,'')
SET @Sql='
SELECT ID,'+@DyColumn+' FRom
(
SELECT * FROM #t
)AS SRC
PIVOT
(
MAX([Text]) FOR Label IN('+@DyColumn+')
)AS Pvt1
'
PRINT @Sql
EXEC(@Sql)
结果
ID Sale LeadSource Display Colour
------------------------------------------
10 Brick Internet Washington Blue