2013-07-03 71 views
1

如何返回显示0响应的行?此查询返回4个ID中的3个和响应数量,但Id 3没有显示,因为它有0个响应。我想它与0在sql查询中返回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
显示

更改joinleft 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 
    ) 
+0

我已经尝试过,没有工作 – user1202606

+2

@ user1202606:除了更改连接类型,移动条件对'sr.SurveyId'从“where”子句到“on”子句 – Andomar

+0

哦,是的,@ Andomar建议使用ON子句更好地说我的更改WHERE。 –

0
; with CTE as 
     (
     ... your query here ... 
     ) 
select * 
from CTE 
union all 
select 0 
,  null 
,  null 
where not exists 
     (
     select * 
     from CTE 
     ) 
+0

你的想法在上面的评论工作。你可以编辑这个来显示on子句的改变,所以我可以接受这个吗?再次感谢 – user1202606

+0

@ user1202606:我的评论只是Brendan Long的答案中的一小部分,所以请务必接受他的回答。 – Andomar