使用任何有效方法旋转特定列值

时间:2018-06-18 15:24:40

标签: sql sql-server sql-server-2012 pivot sql-server-2016

我有一张表格,其中包含如下所示的样本数据。

enter image description here

我正在尝试创建一个旋转表,如下表所示。

enter image description here

所以基本上我需要将attname列中的“catalogID”移动到一个带有其值的新列。 (基于uploadguid和equipmentRef列值的分组/匹配)

我能够使用给定的脚本实现结果,但我认为这不是有效的方法,如果有人有更好的想法,我将非常感谢你的帮助。

这是这个的小提琴。

BEGIN
CREATE TABLE #temp1
(
uploadguid varchar(50) NULL,
attname varchar(50) NULL,
attvalue varchar(50) NULL,
equipmentRef varchar(50) NULL,
)   

Insert Into #temp1 
Values (N'651EF',N'Impact',N'0.123459',N'43398E')
,(N'651EF',N'CatalogID',N'12456',N'43398E')
,(N'541EF',N'alpha',N'0.547623',N'43398E')
,(N'541EF',N'CatalogID',N'36592',N'43398E')
,(N'921EF',N'Beta',N'0.44875',N'43398E')
,(N'921EF',N'CatalogID',N'25894',N'43398E')

Select * from #temp1

select a.*,b.DBcatalogID from #temp1 a inner join (SELECT uploadguid,[CatalogID] AS [DBcatalogID]
        FROM  (select top 100 uploadguid,attname,attvalue,equipmentRef from #temp1 ) a
        PIVOT (max(attvalue) FOR attname IN  ([CatalogID]) ) p) b ON a.uploadguid = b.uploadguid
        WHERE a.attname <> 'CatalogID'

--Drop table #temp1
END

2 个答案:

答案 0 :(得分:2)

为什么不使用join

select t1.*, t2.attvalue as DBcatalogID
from #temp1 t1
    join #temp1 t2 on t1.uploadguid = t2.uploadguid and 
                      t1.equipmentRef = t2.equipmentRef and 
                      t2.attname = 'CatalogID'
where t1.attname != 'CatalogID'

答案 1 :(得分:1)

您可以使用apply

select *, tt.attvalue as DBCatid
from #temp1 t cross apply (
     select top 1 t1.attvalue
     from #temp1 t1
     where t1.uploadguid = t.uploadguid and t1.attname = 'CatalogID'
) tt
where t.attname <> 'CatalogID';