2

我有以下表格:Section, Questions, AnswersQuestionFlagged。显示的响应reviewId=4

Section 1: User Info
      Question 1: What is your name?        Bob Smith
      Question 2: what is your occupation?  Engineer
      Question 3: Your favorite color?  
Section 1: User Location
      Question 1: What is your work location?  New York, NY
      Question 2: What is your office floor?  5th
      Question 3: your street address?  12 wolf street

我需要显示以下内容(需要有关 sql 的帮助):

Review: 4 | Section 1: User Info | 3 questions | 2 Completed | Flagged: Yes

我的桌子:

Section

 SectionID int
 Title  nvarchar(50)
 Description nvarchar(2000)

Question

 QuestionID int
 SectionID int
 QuestionText nvarchar(2000)
 Required boolean
 DisplayOrder int

Response

ResponseID int
QuestionID int  
UserID int int
ReviewId int
AnswerValue nvarchar(1000)

QuestionFlagged

FlaggedID int
QuestionID int
ReviewId int
UserId int  
4

1 回答 1

1

根据您在下面的回复,我已经编辑了查询。我相信这应该会给你你想要的。

select  rsSectionAggregate.ReviewID, 
        rsSectionAggregate.SectionID, 
        Title, 
        QuestionCount, 
        QuestionsAnswered, 
        --Show whether there are flagged questions
        case 
            when QuestionsFlagged > 0 then 'Yes' 
            else 'No' 
        end as QuestionsFlagged
from 
(
    --first aggregate the results by section
    select r.ReviewID, rsSections.SectionID, Title, QuestionCount, COUNT(ResponseID) as QuestionsAnswered
    from
    (
        --this is done as a subquery so we know the total
        --number of questions for each section
        select s.SectionID, Title, COUNT(*) as QuestionCount
        from @Section s
        inner join @Question q on s.SectionID = q.SectionID
        group by s.SectionID, Title
    ) rsSections 
    inner join @Question q on rsSections.SectionID = q.SectionID
    left outer join @Response r on q.QuestionID = r.QuestionID
    group by r.ReviewID, rsSections.SectionID, Title,QuestionCount
) rsSectionAggregate
left outer join
(
    --here we determine if any questions are flagged for a given review
    --by counting them.
    select qf.ReviewID, COUNT(*) as QuestionsFlagged
    from @QuestionFlagged qf
    group by qf.ReviewId
) rsFlagged on rsFlagged.ReviewId = rsSectionAggregate.ReviewId
where rsSectionAggregate.ReviewID = 4

我正在使用这个SQLFiddle

如果您需要创建存储过程的语法,我可以将其编辑到答案中,但这很容易通过 Google 搜索。

于 2012-12-23T17:59:35.483 回答