我有一张表,我将人口统计信息填充到其中,然后使用动态 sql 从中构建一个表。人口统计信息来自调查,一些调查带有复选框。使用复选框,人们可以选择多个值。
所以我需要以逗号分隔的列表形式输入所有选项。
CREATE TABLE Demographics
(
QID NVARCHAR(15)
,userid NVARCHAR(50)
,question NVARCHAR(800)
,choice NVARCHAR(1000)
)
...
...
--Demographics(QID,userid,question,choice)
--'Insert checkbox (type 5)
INSERT INTO Demographics
SELECT CAST(q.QID AS NVARCHAR(15))
,ri.userid
,q.QuestionText
,ac.Choice
FROM ResponseInfo ri --response details
JOIN Responses r ON ri.ResponseID = r.ResponseID --actual response
JOIN Questions q ON r.QID = q.QID --question info
JOIN AnswerChoices ac ON r.QID = ac.QID --answer choice text
WHERE (q.QuestionTypeID = 5 AND q.QID = ac.QID
AND r.IsOther = 0
AND q.QID = 16
)
AND ri.userid IN (SELECT userid FROM @Users) AND r.Response = ac.Sequence
ORDER BY ri.userid
...
dynamic sql stuff
...
EXEC sp_exesql @sql
我的结果如下所示:
users | question_15 | choice_15 | question_16 | choice_16 |
bill | age? | 37 | favorite color? | red |
bill | age? | 37 | favorite color? | green |
但它必须是:
users | question_15 | choice_15 | question_16 | choice_16 |
bill | age? | 37 | favorite color? | red,green |
我试着做
,COALESCE(ac.Choice + ',','') + ac.Choice
它给了我
bill | age? | 37 | favorite color? | red,red |
谁能帮我解决这个问题?