0

我正在寻找填写临时表:

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)

我有一个答案表,我使用问题表中的 questionId 从中提取答案。

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,则最终表格应如下所示:

最终产品表

我不知道这是否意味着超级复杂,但我很难弄清楚。任何帮助是极大的赞赏。

提前致谢。. .

4

2 回答 2

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 
于 2013-06-11T02:45:17.367 回答
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

于 2013-06-11T02:47:19.753 回答