SQL - Transpose

后端 未结 3 1067
死守一世寂寞
死守一世寂寞 2021-01-26 23:33

i have small issues i have been trying to figure out in SQL. I have a table with Item Numbers, Attribute Names and Attribute values. Each Item Number might have same or differen

3条回答
  •  孤独总比滥情好
    2021-01-27 00:25

    You have some syntax errors in your original query

    SELECT * 
      FROM
      (SELECT [ITEM_NUMBER],
              [ATTR_DISPLAY_NAME],
              [ATTRIBUTE_VALUE]
        FROM  tbl_ICC ) AS SourceTable 
      PIVOT (max([ATTRIBUTE_VALUE])
       FOR   [ATTR_DISPLAY_NAME] IN ([color],[size] ))   -- << Add More Attr Display Name Here
      AS PivotTable; 
    

    EDIT - Dynamic Version

    Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName([ATTR_DISPLAY_NAME]) From tbl_ICC  Order by 1 For XML Path('')),1,1,'') 
    Select  @SQL = '
    Select * 
    From (
           Select [ITEM_NUMBER],
                  [ATTR_DISPLAY_NAME],
                  [ATTRIBUTE_VALUE]
            From  tbl_ICC  
         ) A
     Pivot (max(ATTRIBUTE_VALUE) For [ATTR_DISPLAY_NAME] in (' + @SQL + ') ) p'
    Exec(@SQL);
    

提交回复
热议问题