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 に答える