1

如何返回显示 0 个响应的行?此查询返回 4 个 ID 中的 3 个和响应数,但 ID 3 没有显示,因为它有 0 个响应。我希望它显示为 0。

SELECT Count(sr.id) AS 'Responses', 
       qpa.possibleanswertext, 
       qpa.id 
FROM   caresplusparticipantsurvey.questionpossibleanswer AS qpa 
       JOIN caresplusparticipantsurvey.surveyresponse AS sr 
         ON qpa.id = sr.questionpossibleanswerid 
WHERE  ( qpa.id BETWEEN 1 AND 4 ) 
       AND ( sr.surveyid IN (SELECT surveyid 
                             FROM   caresplusparticipantsurvey.surveyresponse AS 
                                    sr 
                             WHERE  sr.questionpossibleanswerid = 138) ) 
GROUP  BY qpa.possibleanswertext, 
          qpa.id 

    99  Very Useful                                         1
    26  Somewhat useful                                         2
    33  I did not complete this CORE requirement this year  4
4

2 回答 2

4

将您的更改join为 a left join,它将NULL用于不匹配的行:

left join CaresPlusParticipantSurvey.SurveyResponse ...

您还需要将过滤器移动到该ON部分,因此删除它:

and (sr.SurveyId in (select SurveyId from CaresPlusParticipantSurvey.SurveyResponse as       sr where sr.QuestionPossibleAnswerId = 138))

并将您的加入更改为:

left join CaresPlusParticipantSurvey.SurveyResponse AS sr 
    ON qpa.id = sr.questionpossibleanswerid
    AND sr.SurveyId IS NULL OR sr.SurveyId in (
        select SurveyId
        from CaresPlusParticipantSurvey.SurveyResponse as sr
        where sr.QuestionPossibleAnswerId = 138
    )
于 2013-07-03T21:19:34.627 回答
0
; with  CTE as
        (
        ... your query here ...
        )
select  *
from    CTE
union all
select  0
,       null
,       null
where   not exists
        (
        select  *
        from    CTE
        )
于 2013-07-03T21:20:14.727 回答