我希望填写临时表:
create table #FinalProduct
(
respondentId int,
respondentNumber nvarchar(7),
questionNumber int,
questionAnswer nvarchar(100)
)
到目前为止,我已经填充了我想要的respondentIds和respondentNumbers。然后我有另一个临时表,我从中提取问题数据:
CREATE TABLE #QuestionData
(
QuestionNumber int NOT NULL IDENTITY,
QuestionText nvarchar(255),
QuestionId int
)
insert into #QuestionData values ('This is question # 1', 101)
insert into #QuestionData values ('This is question # 2', 102)
我有一个答案表,我在其中使用问题表中的问题来提取答案。
CREATE TABLE #AnswerData
(
RespondentNumber nvarchar(7),
QuestionId int,
AnswerText nvarchar(255)
)
insert into #AnswerData values ('9876543',101, 'Answer to #1')
insert into #AnswerData values ('9876543',102, 'Answer to #2')
insert into #AnswerData values ('1234567',101, 'Answer to #1')
insert into #AnswerData values ('1234567',102, 'Answer to #2')
每个respondentNumber都会回答一个问题(并非所有答案都是相同的)。
我希望填充FinalProduct表,以便每个respondentNumber都有一行代表每个问题和答案。例如,如果我有2个respondentNumbers,那么final table应如下所示:
我不知道这是否意味着超级复杂,但我很难搞清楚。任何帮助是极大的赞赏。
提前致谢。 。
答案 0 :(得分:1)
您似乎缺少数据元素,因为respondentID不在您的两个表中,但我认为您只是在这样的连接之后:
SELECT respondentNumber, questionNumber ,AnswerText
FROM AnswerData a
JOIN QuestionData b
ON a.QuestionId = b.QuestionId
您可以将结果选择到新表中:
SELECT respondentNumber, questionNumber ,AnswerText
INTO #FinalProduct
FROM AnswerData a
JOIN QuestionData b
ON a.QuestionId = b.QuestionId
或者您可以将它们插入现有表中:
INSERT INTO #FinalProduct
SELECT respondentNumber, questionNumber ,AnswerText
FROM AnswerData a
JOIN QuestionData b
ON a.QuestionId = b.QuestionId
答案 1 :(得分:1)
给出以下创建代码:
CREATE TABLE QuestionData
(
QuestionNumber int NOT NULL IDENTITY,
QuestionText nvarchar(255),
QuestionId int
)
insert into QuestionData values ('This is question # 1', 101)
insert into QuestionData values ('This is question # 2', 102)
CREATE TABLE AnswerData
(
RespondentNumber nvarchar(7),
QuestionId int,
AnswerText nvarchar(255)
)
insert into AnswerData values ('9876543',101, 'Answer to #1')
insert into AnswerData values ('9876543',102, 'Answer to #2')
insert into AnswerData values ('1234567',101, 'Answer to #1')
insert into AnswerData values ('1234567',102, 'Answer to #2')
create table FinalProduct
(
respondentId int,
respondentNumber nvarchar(7),
questionNumber int,
questionAnswer nvarchar(100)
)
查询:
INSERT INTO FinalProduct
SELECT NULL,a.RespondentNumber,q.QuestionNumber,a.AnswerText
FROM AnswerData a
JOIN QuestionData q
ON a.QuestionId=q.QuestionId
ORDER BY RespondentNumber,q.QuestionNumber
GO
SELECT *
FROM FinalProduct
给出:
RESPONDENTID RESPONDENTNUMBER QUESTIONNUMBER QUESTIONANSWER
(null) 1234567 1 Answer to #1
(null) 1234567 2 Answer to #2
(null) 9876543 1 Answer to #1
(null) 9876543 2 Answer to #2
Sqlfiddle:http://sqlfiddle.com/#!3/30592/3