sql server 中的数据透视表
是的,我已经尝试过代码。我的要求是用户输入年份和月份&价格按日期显示在当年和月份的列中,第一列为 CompetitorID。我希望我的结果如下:
Competitors | day1 | day2 | day3 | day4 ..............|day31 ================================================================ competitor 1| Price | Price | price | price..............|price competitor 2| Price | Price | price | price..............|price competitor 3| Price | Price | price | price..............|price competitor 4| Price | Price | price | price..............|price
我的表结构是:
COMPETITORDETAIL (ID, CompetitorID, oDate, Price)
Yes I've tried the code. My requirement is that user inputs Year and Month & prices are shown date-wise in columns for that year and month, with first column as CompetitorID. I want my result like:
Competitors | day1 | day2 | day3 | day4 ..............|day31 ================================================================ competitor 1| Price | Price | price | price..............|price competitor 2| Price | Price | price | price..............|price competitor 3| Price | Price | price | price..............|price competitor 4| Price | Price | price | price..............|price
My Table structure is:
COMPETITORDETAIL (ID, CompetitorID, oDate, Price)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这容易多了。我编写了一个名为 pivot_query 的存储过程,它使 PIVOT 在 SQL Server 2005+ 中更易于使用。该过程的来源是这里,一些如何使用它的示例是< a href="http://dot-dash-dot.com/files/pivot_query_examples.sql" rel="nofollow noreferrer">此处。
对于您的代码示例:
结果是:
希望有帮助!
This is a lot easier. I wrote a stored proc named pivot_query that makes PIVOT a lot easier to use for SQL Server 2005+. The source for the proc is here, some examples how to use it are here.
For your code example:
which results in:
Hope that helps!
如果您使用 Microsoft SQL-Server,则有一个枢轴函数。但列是静态定义的,因此它的使用受到限制。 (请参阅http://technet.microsoft.com/en-us/library/ ms177410.aspx)
有动态SQL的解决方案,但我最终在代码中解决了这个问题。
If you'r working with Microsoft SQL-Server there is a pivot function. But the columns are defined statically, so it's use is limited. (See http://technet.microsoft.com/en-us/library/ms177410.aspx)
There are solutions with dynamic SQL, but i solved this in the code eventually.
对于 SQL Server 2005、2008
要测试的表和一些数据
周期的开始和天数
动态列 = 动态 sql
继续编写动态查询
连接到变量并执行
返回
For SQL Server 2005, 2008
The table and some data to test
Start of the period and number of days
Dynamic columns = dynamic sql
Continue composing the dynamic query
Concatenate into a variable and execute
Returns