查询将行动态转换为列 [英] query to convert rows into columns dynamically

查看:75
本文介绍了查询将行动态转换为列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在sq l服务器中进行查询,它会动态地将行转换为列。





请提供解决方案

I need a query in sq l server which converts rows into columns dynamically..


please provide a solution

推荐答案

此操作在代数中称为矩阵转置。由于您在标签中仅指定了SQL-Server,因此我查看了Google T-SQL解决方案,但有很多方法:

- 通用方法: http://www.extensionmethod.net/Details.aspx?ID=152 [ ^ ]

- ASP.NET示例:使用C#转换DataTable [ ^ ], http://codemaverick.blogspot.hu/2008/02/transpose-datagrid-or-gridview-by.html [ ^ ]

- T-SQL : http://sqlandme.com/2011/04/20/tsql-transpose-data-using-using-pivot-and-unpivot/ [ ^ ]
This operation is called matrix transposition in algebra. Since you specified only SQL-Server in the tags, I looked on google T-SQL solutions, but there are many approaches:
- Generic approach: http://www.extensionmethod.net/Details.aspx?ID=152[^]
- ASP.NET sample: Transpose a DataTable using C#[^], http://codemaverick.blogspot.hu/2008/02/transpose-datagrid-or-gridview-by.html[^]
- T-SQL: http://sqlandme.com/2011/04/20/tsql-transpose-data-using-using-pivot-and-unpivot/[^]


您好,



您可以使用 Pivot实现此目的。请参阅以下示例。你可能会明白这个想法。



http://www.simple-talk.com/blogs/2007/09/14/pivots-with-dynamic-columns-in-sql-server- 2005 / [ ^ ]



谢谢,

Viprat
Hi,

You can achieve this by using Pivot. See the below example. You might be get the idea.

http://www.simple-talk.com/blogs/2007/09/14/pivots-with-dynamic-columns-in-sql-server-2005/[^]

Thanks,
Viprat


经过大量查询后,我得到了一个查询,我希望这个查询以交叉标签格式动态显示输出



考虑我有一个名为SalesRepor的表有字段Month ,分支机构,销售



after lots of querying i got query that i want this query displays the output in cross tab format dynamically

consider i have table named SalesRepor having fields Month,Branch,Sales

declare @columns varchar(max)
declare @convert varchar(max)
select   @columns = stuff (( select distinct'],[' +  Month
                    from SalesReport
                  
                    for xml path('')), 1, 2, '') + ']'


set @convert =
'select * from (select Month,Branch,Sales from SalesReport) SalesRpt
    pivot(sum(Sales) for Month
    in ('+@columns+')) as pivottable'


execute (@convert)

这篇关于查询将行动态转换为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆