在sql查询上返回0而不是什么

时间:2013-07-03 21:16:48

标签: sql sql-server tsql

如何返回显示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

2 个答案:

答案 0 :(得分:4)

将您的join更改为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
    )

并将您的加入更改为:

{{1}}

答案 1 :(得分:0)

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