SQL 动态透视 - 如何对列进行排序
我正在对包含以下内容的表进行动态数据透视查询:
- OID - OrderID
- Size - 产品的大小
- BucketNum - 尺寸的顺序 应该
- 数量 - 订购的数量
尺寸列包含不同的尺寸,具体取决于 OID。
因此,使用代码发现 这里,我将其放在一起:
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 )
这非常有效,只是列标题(尺寸标签)不是按照基于 bucketnum 列的顺序排列的。 它们是根据尺寸排列的。
我在数据透视后尝试了可选的 Order By,但这不起作用。
如何控制列的显示顺序?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要解决此问题:
以正确的顺序返回列。 您可能必须执行类似的操作,而不是使用
DISTINCT
:You need to fix this:
To return the columns in the right order. You might have to do something like this instead of using
DISTINCT
:我今天刚刚看到这个链接,它使用 CTE 动态构建列列表(大概您可以订购),而不需要动态 sql:
http://blog.stevienova.com/2009/07/13/使用 ctes-to-create-dynamic-pivot-tables-in-sql-20052008/
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/
我遇到了同样的问题,并尝试了上面建议的解决方案,但可能由于我的理解水平,无法使其发挥作用。 我发现一个简单的技巧是创建一个临时表,其中的列标题使用 Order by 语句正确排序,然后将该列表拉入设置动态数据透视查询列名称的变量。
例如,请客
吃饭。
希望对某人有帮助。
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.
Worked a treat.
Hope that helps someone.