0

我有代码将来自许多表的数据放在一起,这些数据与用户对特定课程的所有问题的反应有关。响应如下所示:

userid|lesson|question |response|label|weight|duration_seconds
========================================================================
bob   |first |loc_nameA|4       |R9   |3.5   |189
bob   |first |loc_nameB|2       |R7   |4.5   |113
…

需要制作一份报告,将所有响应显示在一行中。因此,对于每个问题,我需要将响应与其相应的标签、权重和持续时间一起显示到一列中,如下所示:

userid|lesson|1_resp|1_labl|1_weig|1_dura|2_resp|3_labl|3_weig|3_dura|4_resp…
========================================================================
bob   |first |4     |R9    |3.5   |189   |2     |R7    |4.5   |113   |1

或者,使用“问题”列值作为动态列名的一部分。目前它们都有像 L1Q1 这样的逻辑名称,所以只有 1,2,3 就足以作为列名,但情况可能并非总是如此:

userid|lesson|loc_nameA_resp|loc_nameA_labl|loc_nameA_weig|loc_nameA_dura|loc_nameB_resp|loc_nameB_labl|loc_nameB_weig|loc_nameB_dura|loc_nameC_resp…
================================================================================================================================================
bob   |first |4             |R9            |3.5           |189           |2             |R7            |4.5           |113           |1

我一直在阅读有关数据透视表的信息,但所有示例似乎都比我所描述的更有限。SQL Server 2005 如何做到这一点?我应该使用别的东西吗?有没有更简单的方法?

4

1 回答 1

1

您可以使用动态 SQL 来解决这个问题——或者如果它只是针对一组数据,则手动编写它。在这两种情况下,您最终都会得到如下所示的内容:

SELECT R1.userid, R1.lesson, 
       R1.response as loc_nameA_resp, R1.lable as loc_nameA_labl, R1.weight as loc_nameA_weig, R1.duration_seconds as loc_nameA_dura,
       R2.response as loc_nameB_resp, R2.lable as loc_nameB_labl, R2.weight as loc_nameB_weig, R2.duration_seconds as loc_nameB_dura,
--- etc for each question
FROM user U
JOIN response R1 on R1.userid = u.userid and R1.lesson = 'first' and R1.question = 'loc_nameA'
JOIN response R2 on R2.userid = u.userid and R2.lesson = 'first' and R2.question = 'loc_nameB'
--- etc for each question
WHERE
   U.userid = 'bob' -- this does not need to be bob, whatever user you want.

给你,测试和一切。

DECLARE @sqlSelectList varchar(max);
DECLARE @sqlJoinList varchar(max);

SELECT @sqlSelectList = '', @sqlJoinList='';

WITH Questions AS
(
  SELECT DISTINCT question
  FROM ResultsChoices
)
SELECT -- We use the question as the alias for join uniqueness,
       -- We could increment a number but why bother?
  @sqlJoinList = @sqlJoinList +
     ' JOIN ResultsChoices '+question+' on '+question+'.userid = u.userid and '+question+'.question = '''+question+'''', 
  @sqlSelectList = @sqlSelectList +
     ', '+question+'.response as '+question+'_resp, '+question+'.label as '+question+'_labl, '+question+'.weight as '+question+'_weig, '+question+'.duration_seconds as '+question+'_dura '
FROM Questions;

DECLARE @sql NVARCHAR(max);

SET @sql = N'SELECT DISTINCT u.userid ' + @sqlSelectList + N' FROM #ResultsChoices u ' + @sqlJoinList;

EXEC sp_executesql @sql
于 2012-07-10T04:23:20.940 回答