1

Possible Duplicate:
Poor Man’s SQL Pivot. List Questions as Columns and Answers per User in one row

I have the following query to first pull 12 records for each of my foreign keys(null values in the case of missing records), and then turn all 12 records per foreign key into a column. The code below however, generates the 12 rows but fails to turn all the rows into columns. Instead it does the transform for just one of my foreign key IDS and then stops.

Please help me pivot this properly so that for each ProductID, I get a row. Thanks in advance.

  DECLARE @colsUnpivot AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),
    @colsPivot as  NVARCHAR(MAX)

    --BEGIN TRY
           IF EXISTS
                (
                            SELECT *
                            FROM tempdb.dbo.sysobjects
                            WHERE ID = OBJECT_ID(N'tempdb..#ManufacturerAttributes')
                )
                BEGIN
                            DROP TABLE #ManufacturerAttributes
                END
    Create table #ManufacturerAttributes
    ( 
            ProductID uniqueIdentifier,
             PAID uniqueidentifier,
            MfgAttrLabel varchar(50),
            MfgAttrVal varchar(3072),
            MfgAttrUOM varchar(50), 
            rowindex int
    )
    ;With Number
As
(
 Select 1 as rownum union all  Select 2 union all Select 3 union all Select 4 union all Select 5 union all Select 6 union all Select 7 union all Select 8 union all Select 9 union all Select 10 union all Select 11 union all Select 12   
),
ProductDetail 
as 
(
   select P.ProdID, N.rownum from IDWProduct P cross join Number N
)
Insert into #ManufacturerAttributes
Select  ProdID  , PAVAttributeID,PANAme, PAVValue, UOMLabel, P.rownum
 from ProductDetail P
Left join (select Pr.*, row_number() over (partition by PAVProductID order by PAVID) as Rn from IDWProductAttributeValues Pr ) Pr ON rownum = Pr.Rn And PAVProductID = ProdID  
left join IDWUnitofMeasures on Pr.PAVUOM = UOMID 
left join IDWAttributes  A on Pr.PAVAttributeID = A.PAID  AND A.PAIsManufacturerSpecific = 1

 Select * from #ManufacturerAttributes

  select @colsUnpivot = stuff((select ','+quotename(C.name)
         from tempdb.sys.columns as C
         where C.object_id = object_id('tempdb..#ManufacturerAttributes')  
         for xml path('')), 1, 1, '')

-- select @colsUnpivot

 select @colsPivot = STUFF((SELECT  ','  + quotename(c.name   + cast(t.rn as varchar(10)))
                    from
                    (
                      select row_number() over(partition by ProductID   order by ProductID) rn  from #ManufacturerAttributes
                    ) t
                     cross apply 
                      tempdb.sys.columns  as C
                   where C.object_id = object_id('tempdb..#ManufacturerAttributes')   
                   group by c.name, t.rn
                   order by t.rn
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

 --select @colsPivot
   set @query 
  ='select *
      from
      (
        select ProductID, PAID, RowIndex,
            col + cast(rn as varchar(10)) new_col,
            val 
         from 
        (
          select  
          Cast (ProductID as NVarchar(3072)) ProductID
          ,Cast(PAID as NVarchar(3072)) PAID
           ,Cast (MfgAttrLabel  as NVarchar(3072)) MfgAttrLabel
           ,Cast (MfgAttrVal as NVarchar(3072)) MfgAttrVal
           ,Cast (MfgAttrUOM as NVarchar(3072))  MfgAttrUOM  
           ,Cast(rowindex as NVarchar(3072)) rowindex
            ,row_number() over(partition by ProductID order by ProductID) rn
          from  #ManufacturerAttributes

        ) x
        unpivot
        (
          val
          for col in ('+ @colsunpivot +')
        ) u
      ) x1
      pivot
      (
        max(val)
        for new_col in
          ('+ @colspivot +')
      ) p'


    --  Print @query

exec(@query)    

SQLFiddle complete with Script

Community
  • 1
  • 1
Kobojunkie
  • 6,375
  • 31
  • 109
  • 164
  • 2
    Can you create a [SQL Fiddle](http://sqlfiddle.com/) with some sample data? – Taryn Oct 11 '12 at 10:37
  • @bluefeet, I added an SQLFiddle with code – Kobojunkie Oct 11 '12 at 15:22
  • PRODUCTID1,PAID1, MFGATTRLABEL1,MFGATTRVAL1,MFGATTRUOM1,ROWINDEX1, PRODUCTID2, PAID2, MFGATTRLABEL2,MFGATTRVAL2,MFGATTRUOM2, ROWINDEX2, PRODUCTID3,PAID3,MFGATTRLABEL3,MFGATTRVAL3,MFGATTRUOM3,ROWINDEX3 . . . ... through 12 – Kobojunkie Oct 11 '12 at 16:59
  • what is wrong with this fiddle -- http://sqlfiddle.com/#!3/10876/8 ? – Taryn Oct 11 '12 at 17:02
  • It returns just one row. No matter how many entries I have, I still seem to get only the one row of data at the end, instead of one row per ProductID – Kobojunkie Oct 11 '12 at 17:22
  • can you add data to the fiddle for all of the tables? right now there is only data in the `IDWProduct` table. – Taryn Oct 11 '12 at 17:25
  • Yes, I want to add more but I think I have reached the 8000 characters limit. – Kobojunkie Oct 11 '12 at 18:06
  • Additional data is in here though http://sqlfiddle.com/#!3/10876/9 – Kobojunkie Oct 11 '12 at 18:33
  • @bluefeet, the fiddle at sqlfiddle.com/#!3/10876/8 ? has 2 Product table data, but it only generates for one of them – Kobojunkie Oct 11 '12 at 18:50
  • This is supposed to, for every Product ID in the product table, generate a row consisting of the 12 sets, even when there is no data available in the other tables. What is happening on my end is that even when there are product IDs with values in the other tables, only one row is created still. – Kobojunkie Oct 11 '12 at 20:36
  • I can't seem to do that as I get the message "Your schema ddl is too large (more than 8000 characters). Please submit a smaller DDL." see http://sqlfiddle.com/#!3/10876/9 – Kobojunkie Oct 11 '12 at 21:01
  • please create a separate sql fiddle with some of the other tables data, I will then place that data into my sql server for testing. – Taryn Oct 11 '12 at 21:05
  • I have that here http://sqlfiddle.com/#!3/10876/9 – Kobojunkie Oct 11 '12 at 21:15
  • Ok. I have the following files. , http://sqlfiddle.com/#!3/12457, http://sqlfiddle.com/#!3/980b7, http://sqlfiddle.com/#!3/e7f21 , http://sqlfiddle.com/#!3/56a25 – Kobojunkie Oct 11 '12 at 21:46
  • @Kobojunkie when you run the query in this fiddle in your database - do you even start with usable data -- http://sqlfiddle.com/#!3/10876/11 ? It is hard to see because all of the columns have null values? – Taryn Oct 11 '12 at 23:16
  • Well, like I said, the query needs to generate, for every productID, 12 attribute rows, even if all null populated, which are then turned into a row with 12 sets for the each Product ID. I am able to get the first part working using the query, however when it is time to turn the generated row (only one productID gets a row) the others just disappear. – Kobojunkie Oct 12 '12 at 00:21

0 Answers0