我有一些代码,汇集了许多表格中有关用户对特定课程所有问题的回答的数据。回复看起来像这样:
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完成此操作?我应该使用其他东西吗?有更简单的方法吗?
答案 0 :(得分: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