代码之家  ›  专栏  ›  技术社区  ›  Gowtham Ramamoorthy

使用任何有效方法透视特定列的值

  •  1
  • Gowtham Ramamoorthy  · 技术社区  · 7 年前

    我有一个表,其中有一个样本数据如下所示。

    enter image description here

    我正试图从上表创建一个透视表,如下所示。

    enter image description here

    所以基本上我需要将attname列中的“catalogid”移动到一个新列中,并显示其值。(基于uploadguid和equipmentref列值的分组/匹配)

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

    这是这个的sql小提琴。

    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 回复  |  直到 7 年前
        1
  •  2
  •   sgeddes    7 年前

    为什么不直接用 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'
    
        2
  •  1
  •   Yogesh Sharma    7 年前

    你可以使用 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';