Using PIVOT in SQL Server 2008(在 SQL Server 2008 中使用 PIVOT)
问题描述
假设我有一些数据,无论是在 SQL Server 2008 表中还是在 [表] 类型的变量中:
我想检索数据作为如下所示的结果集:
我怀疑 PIVOT 运算符是我需要的(根据 thispost,无论如何),但我不知道如何开始,尤其是当表中 question_id 行的数量可能会有所不同时.在上面的示例中,它是 5,但在另一个查询中,该表可能填充有 7 个不同的问题.
实际上,您最好在客户端执行此操作.假设您正在使用 Reporting Services,根据您的第一个结果集获取数据并使用矩阵显示它,在行组中使用 author_id 和 review_id,在列组中使用 question_id,在中间使用 MAX(answer_id).
查询是可行的,但您现在需要动态 SQL.
...类似:
Let's say I have some data, either in a SQL Server 2008 table or a [table]-typed variable:
I want to retrieve the data as a result set that looks like this:
I suspect the PIVOT operator is what I need (according to this post, anyway), but I can't figure out how to get started, especially when the number of question_id rows in the table can vary. In the above example, it's 5, but in another query the table might be populated with 7 distinct questions.
Actually, you'd be better off doing this in the client. Suppose you're using Reporting Services, get the data as per your first result set and display it using a Matrix, with author_id and review_id in the Row Group, question_id in the Column Group, and MAX(answer_id) in the middle.
A query is doable, but you'd need dynamic SQL right now.
...something like:
这篇关于在 SQL Server 2008 中使用 PIVOT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!