0

我正在使用 Lime Survey 并最终希望将 Crystal Reports 用于我的最终输出,并且正在寻求有关干预步骤的帮助。我的每条回复记录有一行,有 100 多个问题,分为几个部分。输出看起来像一个交叉表,每个问题有一列,但我需要先对数据进行反透视,然后才能在 Crystal Reports 中使用它。

根据调查,可能有 4 个部分,也可能多达 15 个。那么,有没有办法根据部分的数量使用 sql 动态执行此操作?

举例说明——在 Excel 中,Lime Survey 的输出如下所示


ID  Subject Relationship    1Section    1SQuestion1 1SQuestion2 2Section    2SQuestion1 2SQuestion2
1   John    Boss            1Section    2           4           2Section    3           4
2   John    Peer            1Section    4           3           2Section    2           5
3   Sally   Boss            1Section    3           3           2Section    4           5
4   Sally   Peer            1Section    5           6           2Section    1           3

这就是我最终需要它的样子

ID 主题关系 1Section Col5 Col6
1 John Boss 1第 1S 题 1 2
1 John Boss 1第 1S 题 2 4
2 John Peer 1Section 1SQuestion1 4
2 John Peer 1Section 1SQuestion2 3
3 莎莉老板 1Section 1SQuestion1 3
3 Sally Boss 1 第 1S 题 2 3
4 Sally Peer 1Section 1SQuestion1 5
4 Sally Peer 1Section 1SQuestion2 6
1 John Boss 2 第 2S 题 1 3
1 John Boss 2 第 2S 题 2 4
2 John Peer 2第 2S 问题 1 2
2 John Peer 2第 2S 问题 2 5
3 Sally Boss 2第 2S 问题 1 4
3 Sally Boss 2 第 2S 问题 2 5
4 Sally Peer 2Section 2SQuestion1 1
4 Sally Peer 2Section 2SQuestion2 3

谢谢

4

1 回答 1

0

如果要在 sql 中执行此数据转换,则可以使用UNION ALL查询:

select id, subject, relationship, `1Section`, '1sQuestion1' col5, `1sQuestion1` col6
from yourtable
union all
select id, subject, relationship, `1Section`, '1sQuestion2' col5, `1sQuestion2` col6
from yourtable
union all
select id, subject, relationship, `2Section`, '2sQuestion1' col5, `2sQuestion1` col6
from yourtable
union all
select id, subject, relationship, `2Section`, '2sQuestion2' col5, `2sQuestion2` col6
from yourtable

请参阅SQL Fiddle with Demo。这给出了结果:

| ID | SUBJECT | RELATIONSHIP | 1SECTION |        COL5 | COL6 |
---------------------------------------------------------------
|  1 |    John |         Boss | 1Section | 1sQuestion1 |    2 |
|  2 |    John |         Peer | 1Section | 1sQuestion1 |    4 |
|  3 |   Sally |         Boss | 1Section | 1sQuestion1 |    3 |
|  4 |   Sally |         Peer | 1Section | 1sQuestion1 |    5 |
|  1 |    John |         Boss | 1Section | 1sQuestion2 |    4 |
|  2 |    John |         Peer | 1Section | 1sQuestion2 |    3 |
|  3 |   Sally |         Boss | 1Section | 1sQuestion2 |    3 |
|  4 |   Sally |         Peer | 1Section | 1sQuestion2 |    6 |
|  1 |    John |         Boss | 2Section | 2sQuestion1 |    3 |
|  2 |    John |         Peer | 2Section | 2sQuestion1 |    2 |
|  3 |   Sally |         Boss | 2Section | 2sQuestion1 |    4 |
|  4 |   Sally |         Peer | 2Section | 2sQuestion1 |    1 |
|  1 |    John |         Boss | 2Section | 2sQuestion2 |    4 |
|  2 |    John |         Peer | 2Section | 2sQuestion2 |    5 |
|  3 |   Sally |         Boss | 2Section | 2sQuestion2 |    5 |
|  4 |   Sally |         Peer | 2Section | 2sQuestion2 |    3 |
于 2013-01-24T14:38:39.247 回答