CF8 - 循环求和

Ali*_*ias 0 mysql coldfusion loops addition coldfusion-8

我有一个问题:

<cfquery name="getDesc" datasource="#ds#">
  SELECT
    desc,
    SUM(charge) as cost,
    COUNT(*) as cnt
  FROM
    product
  WHERE Length(desc) > 0
</cfquery>
Run Code Online (Sandbox Code Playgroud)

然后填充表格:

<table>
  <tbody>
      <tr>
        <th>Description</th>
        <th>Amount of Charges</th>
        <th>Cost (&pound;)</th>
      </tr>

      <cfoutput query="getDesc">
      <tr>
        <td>
          #HTMLEditFormat(getDesc.desc)# <br />
        </td>     
        <td>
          #HTMLEditFormat(getDesc.cnt)# <br />
        </td>
        <td>
            #HTMLEditFormat(getDesc.cost)# <br />
        </td>
      </tr>
    </cfoutput>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

我的问题是,我想组合两行具有相同值的表,并将它们的两个计数加在一起.

到目前为止,我有:

<table>
  <tbody>
      <tr>
        <th>Description</th>
        <th>Amount of Charges</th>
        <th>Cost (&pound;)</th>
      </tr>

      <cfoutput query="getDesc">
      <tr>
        <cfif getDesc.desc EQ 'No Charge' OR getDesc.desc EQ 'No Charge (2)'>
          <td>
            No Charge & (2)
          </td>
          <td>
            <cfset cntSum = arraySum(getDesc['cnt'])>
            #cntSum#
          </td>
        <cfelse>
        <td>
          #HTMLEditFormat(getDesc.desc)# <br />
        </td>     
        <td>
          #HTMLEditFormat(getDesc.cnt)# <br />
        </td>
        </cfif>
        <td>
            #HTMLEditFormat(getDesc.cost)# <br />
        </td>
      </tr>
    </cfoutput>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

但是这给了我两行'No Charge&(2)',并且count是表中所有其余行的总和,而不仅仅是我想要的两行.

希望这是有道理的.

bar*_*nyr 5

我会更改您的查询以获取您需要的数据.以下是我刚刚提出的我认为符合您要求的内容:

  SELECT
    CASE `desc` WHEN 'No Charge (2)' THEN 'No Charge' ELSE `desc` END,
    SUM(charge) as cost,
    COUNT(*) as cnt
  FROM
    product
  WHERE Length(`desc`) > 0
  group by CASE `desc` WHEN 'No Charge (2)' THEN 'No Charge' ELSE `desc` END
Run Code Online (Sandbox Code Playgroud)

case语句将'No Charge(2)'更改为'No Charge',因此这两种值只有一行.group by语句使mySQL执行求和,并根据'desc'的不同值计算一次.