我正在开发一个允许可配置问题和答案的应用程序。目前最多可以有 20 个答案,但可能更少。
我的结构如下:
问题
+----+--------+--------------+-------------+
| ID | FormId | QuestionText | AnswerField |
+----+--------+--------------+-------------+
| 1 | 1 | Name | Answer01 |
| 2 | 1 | Address | Answer02 |
| 3 | 1 | Phone | Answer03 |
| 4 | 1 | Email | Answer04 |
| 5 | 2 | First Name | Answer01 |
| 6 | 2 | Surname | Answer02 |
+----+--------+--------------+-------------+
答案
+----+--------+----------+------------+--------------+--------------+----------------+----------+----------+
| ID | FormId | RecordId | Answer01 | Answer02 | Answer03 | Answer04 | Answer05 | Answer06 |
+----+--------+----------+------------+--------------+--------------+----------------+----------+----------+
| 1 | 1 | 1 | Bob Smith | Bobs Address | 01234 111222 | bob@smith.com | Null | Null |
| 2 | 1 | 2 | Joe Bloggs | Joes Address | 04321 333444 | joe@bloggs.com | Null | Null |
| 3 | 2 | 3 | David | Jones | Null | Null | Null | |
+----+--------+----------+------------+--------------+--------------+----------------+----------+----------+
所以在 Questions 表中,AnswerField Answer01 映射到 Answers 表中的 Answer01 列
我想做的是得到一个看起来像这样的结果集:
对于表格 ID 1 和记录 ID 1:
+--------------+---------------+
| QuestionText | Answer |
+--------------+---------------+
| Name | Bob Smith |
| Address | Bobs Address |
| Phone | 01234 111222 |
| Email | bob@smith.com |
+--------------+---------------+
然后对于表单 id 2 和记录 id 3:
+--------------+---------+
| QuestionText | Answer |
+--------------+---------+
| First Name | David |
| Surname | Jones |
+--------------+---------+
我尝试使用数据透视表:
SELECT QuestionText, Answer01, Answer02, Answer03, Answer04
FROM (
SELECT DISTINCT Q.AnswerField, Q.QuestionText, Q.ID, A.Answer01, A.Answer02, A.Answer03, A.Answer04
FROM Questions Q
INNER JOIN Answers A ON A.FormId= Q.FormId
WHERE A.ID = 17
)
AS src
PIVOT (MAX(question_id) FOR Answer IN(answer_01, answer_02, answer_03, answer_04)) AS pvt
但这重复了所有列中的答案:
+--------------+-----------+--------------+--------------+---------------+
| QuestionText | Answer01 | Answer02 | Answer03 | Answer04 |
+--------------+-----------+--------------+--------------+---------------+
| Name | Bob smith | Bobs Address | 01234 111222 | bob@smith.com |
| Address | Bob smith | Bobs Address | 01234 111222 | bob@smith.com |
| Phone | Bob smith | Bobs Address | 01234 111222 | bob@smith.com |
| Email | Bob smith | Bobs Address | 01234 111222 | bob@smith.com |
+--------------+-----------+--------------+--------------+---------------+
这显然是不对的。
任何人都可以建议如何在 SQL Server 存储过程中完成此操作吗?