我有參與者和答案的基表,結構如下:SQL查詢的問題:如何合併兩個列表
ParticipantId, BusUnitId, QuestionNum, Answer.
在此表中,QuestionNum範圍,比方說,從1到6。我還有另外兩個表,將QuestionNum鏈接到實際問題表,BusUnitQuestions和ParticipantQuestions。對於每個QuestionNum,我都必須根據QuestionId獲取實際的問題文本。
BusUnitId, QuestionId
ParticipantId, QuestionId
現在從1至6 BusUnitQuestions假設記錄與QuestionNum有3條記錄,所以QuestionNum 1至3必須加入對QuestionId的從BusUnitQuestions問題,QuestionNum 4到6必須加入到問題在ParticipantQuestions的QuestionId上。我假設我需要在BusUnitQuestions的子查詢中使用ROW_NUMBER()加入到我的答案表中,但之後我就失去了。
如果有人根本理解我,你有什麼建議嗎?
下面是一個示例設置。在此,參與者回答了5個問題(1至5)。前三個問題由參與者的部門設定,最後兩個由參與者選擇。實際上,部門和參與者可以選擇5個以上的問題。我需要將Answers表加入Answers表中,使用AnswersQuestions和ParticipantQuestions中對應於Answers表中QuestionNum的行號。
create table Answers (AnswerId int identity(1,1), ParticipantId int, DeptId int, QuestionNum int, AnswerScore int)
create table Dept_Question (DqId int identity(1,1), DeptId int, QuestionId int)
create table Particpant_Question (PqId int identity(1,1), ParticipantId int, QuestionId int)
create table Questions (QuestionId int identity(1,1), QuestionText nvarchar(200))
insert Questions (QuestionText) values ('What is a duck?')
insert Questions (QuestionText) values ('How much do you weigh?')
insert Questions (QuestionText) values ('Why does orange fit?')
insert Questions (QuestionText) values ('Who pokes the fish?')
insert Questions (QuestionText) values ('Why no cow bells?')
insert Dept_Question (DeptId, QuestionId) values (3, 3)
insert Dept_Question (DeptId, QuestionId) values (3, 4)
insert Dept_Question (DeptId, QuestionId) values (3, 1)
insert Particpant_Question(ParticipantId, QuestionId) values (1, 2)
insert Particpant_Question(ParticipantId, QuestionId) values (1, 4)
insert Answers (ParticipantId, DeptId, QuestionNum, AnswerScore) values (1, 3, 1, 63)
insert Answers (ParticipantId, DeptId, QuestionNum, AnswerScore) values (1, 3, 2, 89)
insert Answers (ParticipantId, DeptId, QuestionNum, AnswerScore) values (1, 3, 3, 44)
insert Answers (ParticipantId, DeptId, QuestionNum, AnswerScore) values (1, 3, 4, 54)
insert Answers (ParticipantId, DeptId, QuestionNum, AnswerScore) values (1, 3, 5, 72)
您提供一些樣本DDL? – codingbadger 2010-05-11 07:51:24
要添加到Barry的請求中,請發佈DDL(CREATE TABLE語句),每個表的一些示例數據(希望作爲INSERT語句)以及預期結果。如果我們可以在數據庫中編寫實際的SQL語句並在將其放入答案之前進行調試,那麼人們可以更容易地回答這樣的問題。 – 2010-05-11 07:56:49
我已經添加了一個安裝腳本。 – ProfK 2010-05-11 13:56:58