SQL Dynamic Pivot - how to order columns

白昼怎懂夜的黑 提交于 2019-11-26 08:33:31

问题


I\'m working on a dynamic pivot query on a table that contains:

  • OID - OrderID
  • Size - size of the product
  • BucketNum - the order that the sizes should go
  • quantity - how many ordered

The size column contains different sizes depending upon the OID.

So, using the code found here, I put this together:

DECLARE @listCol VARCHAR(2000)
DECLARE @query VARCHAR(4000)

SELECT  @listCol = STUFF(( SELECT distinct  \'], [\' + [size]
                           FROM     #t
                         FOR
                           XML PATH(\'\')
                         ), 1, 2, \'\') + \']\'


SET @query = \'SELECT * FROM
      (SELECT OID,  [size], [quantity]
            FROM #t 
            ) src
PIVOT (SUM(quantity) FOR Size
IN (\' + @listCol + \')) AS pvt\'


EXECUTE ( @query )

This works great except that the column headers (the sizes labels) are not in the order based upon the bucketnum column. The are in the order based upon the sizes.

I\'ve tried the optional Order By after the pivot, but that is not working.

How do I control the order in which the columns appear?

Thank you


回答1:


You need to fix this:

SELECT  @listCol = STUFF(( SELECT distinct  '], [' + [size]
                           FROM     #t
                         FOR
                           XML PATH('')
                         ), 1, 2, '') + ']'

To return the columns in the right order. You might have to do something like this instead of using DISTINCT:

SELECT [size]
FROM     #t
GROUP BY [size]
ORDER BY MIN(BucketNum)



回答2:


SELECT @listCol = STUFF(
        (SELECT DISTINCT ',' + QUOTENAME(size) AS [size]
        FROM #t
        ORDER BY [size]
        FOR XML PATH('')



回答3:


I saw this link just today, which uses a CTE to build the column list (which, presumably, you could order) on the fly without the need for dynamic sql:

http://blog.stevienova.com/2009/07/13/using-ctes-to-create-dynamic-pivot-tables-in-sql-20052008/




回答4:


I had the same problem and tried the solution suggested above but, probably due to my level of understanding, couldn't get it to work. I found a simple hack was to create a Temp table with the column headers ordered correctly using Order by statements and then pull in that list to the variable that sets the dynamic pivot query column names.

e.g.

SELECT WeekNum INTO #T3 
FROM #T2 
GROUP BY WeekNum 
ORDER BY MIN(WeekNum) 

SELECT @ColumnName1 = ISNULL(@ColumnName1 + ',','') + QuoteName(WeekNum) 
FROM (SELECT WeekNum From #T3) AS WeekNum

Worked a treat.

Hope that helps someone.



来源:https://stackoverflow.com/questions/1122117/sql-dynamic-pivot-how-to-order-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!