由于group by,行会成倍增加

时间:2013-10-31 08:34:50

标签: mysql sql coldfusion group-by

我正在查询几个表格以获得问题的每个答案的计数。在这里,我正在做的是进行调查,我们可能会在完成调查时提出一些答案选项,我们需要获得调查的统计数据,然后我们需要计算问题的每个答案的数量。

这是我的查询。

SELECT s.NAME AS surveyname,
    COUNT(r.answer_id) AS totalAnswer,
    q.id AS questionid,
    q.question AS question,
    a.answer AS answer,
    COUNT(r.textbox) AS totalTextbox,
    COUNT(r.textboxmulti) AS totalTextboxmulti,
    qt.template AS template,
    s.NAME AS surveyname,
    COUNT(r.other) AS other
FROM surveys s
INNER JOIN survey_results AS sr
    ON s.id = sr.survey_id
INNER JOIN results AS r
    ON sr.id = r.surveyresults_id
INNER JOIN questions AS q
    ON r.question_id = q.id
INNER JOIN questiontypes AS qt
    ON q.questiontype_id = qt.id
LEFT JOIN answers AS a
    ON r.answer_id = a.id
WHERE s.id = < cfqueryparam cfsqltype = "cf_sql_integer" value = "#arguments.surveyid#" >
GROUP BY q.id,
    a.id
ORDER BY a.rank

这个查询工作正常我想要的。但问题是在视图上显示结果时,虽然我使用cfoutout属性组和列名称questionid,但问题会与答案数相乘。任何人都可以帮助我如何防止问题与答案数量相乘?

这是我显示调查结果的方式

<cfoutput query="rc.data.questions" group="questionid">
   <cfswitch expression="#rc.data.questions.template#">
      <cfcase value="multiplechoice">
         <table class="table table-striped table-hover">
            <thead>
               <tr>
                  <th width="50%">#rc.data.questions.question#</th>
                  <th></th>
                  <th>
                     <div class="center">Response Count</div>
                  </th>
               </tr>
            </thead>
            <cfoutput>
               <tbody>
                  <tr>
                     <td width="60%">#rc.data.questions.answer#</td>
                     <td>
                        <div class="center">#rc.data.questions.totalanswer#</div>
                     </td>
                  </tr>
            </cfoutput>
            <cfif structKeyExists(rc.data.questions, "totalother") AND rc.data.questions.template EQ 'multiplechoiceother' OR rc.data.questions.template EQ 'multiplechoicemultiother'> 
            <tr>
            <td><a href="#buildurl(action='survey.text_other',querystring='id=#questionid#')#" target="_blank">View other Text answers</a></td>
            <td><div class="center">#rc.data.questions.totalother#</div></td>
            </tr>
            </cfif>
            </tbody>
         </table>
         </table>
      </cfcase>
   </cfswitch>
</cfoutput>

1 个答案:

答案 0 :(得分:2)

order by子句中字段的顺序必须与您要使用cfoutput的group属性的顺序相匹配。如果你想这样做:

<cfoutput query="SomeQuery" group="field1">
    #data for this grouping#
    <cfoutput group="field2">
        #data for this grouping#
        <cfoutput>
            #ungrouped data#
        </cfoutput>
    </cfoutput>
</cfoutput>

然后您的查询必须以:

结束
order by field1, field2, other_fields_if_appropriate