加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

在SQL Server 2008中使用PIVOT

发布时间:2020-12-12 07:00:50 所属栏目:MsSql教程 来源:网络整理
导读:假设我在SQL Server 2008表或[table] -typed变量中有一些数据: author_id review_id question_id answer_id88540 99001 1 71988540 99001 2 72088540 99001 3 72188540 99001 4 72288540 99001 5 72336414 24336 1 30236414 24336 2 30336414 24336 3 304364
假设我在SQL Server 2008表或[table] -typed变量中有一些数据:
author_id     review_id     question_id     answer_id
88540         99001         1               719
88540         99001         2               720
88540         99001         3               721
88540         99001         4               722
88540         99001         5               723
36414         24336         1               302
36414         24336         2               303
36414         24336         3               304
36414         24336         4               305
36414         24336         5               306

我想检索数据作为结果集,如下所示:

author_id     review_id     1     2     3     4     5
88540         99001         719   720   721   722   723
36414         24336         302   303   304   305   306

我怀疑PIVOT操作符是我需要的(根据this post,无论如何),但我无法弄清楚如何开始,特别是当表中的question_id行数可能不同时.在上面的示例中,它是5,但在另一个查询中,该表可能会填充7个不同的问题.

解决方法

实际上,你最好在客户端做这件事.假设您正在使用Reporting Services,请根据您的第一个结果集获取数据,并使用Matrix显示数据,行组中包含author_id和review_id,列组中包含question_id,中间包含MAX(answer_id).

查询是可行的,但您现在需要动态SQL.

…就像是:

DECLARE @QuestionList nvarchar(max);
SELECT @QuestionList = STUFF(
(SELECT ',' + quotename(question_id)
FROM YourTable
GROUP BY question_id
ORDER BY question_id
FOR XML PATH('')),1,2,'');

DECLARE @qry nvarchar(max);
SET @qry = '
SELECT author_id,review_id,' + @QuestionList + 
FROM (SELECT author_id,question_id,answer_id
      FROM YourTable
     ) 
PIVOT
(MAX(AnswerID) FOR question_id IN (' + @QuestionList + ')) pvt
ORDER BY author_id,review_id;';

exec sp_executesql @qry;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读