CF获取数据库查询中列的总和

CF Getting the sum of a column on a database query

我正在尝试使用 ColdFusion 和 MS Sql 计算列的总数。

有人能告诉我我忽略了什么吗?我的位置总计总数不是对列求和,而是出于某种原因只取该列中的最后一个数字。我哪里错了?

<cfset result = {} /> 
<cftry> 
    <cfquery datasource="#application.dsn#" name="GetLocationInfo">
        SELECT *
        FROM cl_checklists
    </cfquery>

    <cfcatch type="any"> 
        <cfset result.error = CFCATCH.message > 
        <cfset result.detail = CFCATCH.detail > 
    </cfcatch> 
</cftry> 

<table border="1" id="Checklist_Stats">
    <thead>
        <th><strong>Location</strong></th>
        <th><strong>Percent of Total Checklists</strong></th>
        <th><strong>Location Total</strong></th> 
    </thead>
    <tbody>
    <cfquery name="allLocCode" dbtype="query">
        SELECT DISTINCT trans_location, COUNT(*) AS locationCount FROM GetLocationInfo GROUP BY trans_location ORDER BY trans_location 
    </cfquery>
     <cfloop query="allLocCode">
      <cfset thisLocationName = trim(allLocCode.trans_location) />

      <cfquery name="allLocCodeForLocationQry" dbtype="query">
          SELECT trans_location,count(trans_location) AS locCntr FROM GetLocationInfo WHERE trans_location='#thisLocationName#' GROUP BY trans_location ORDER BY trans_location
      </cfquery>
        <cfset columnSum = ArraySum(allLocCodeForLocationQry['locCntr'])>
      <cfoutput query="allLocCodeForLocationQry">
      <tr>
        <td><strong>#thisLocationName#</strong></td>
        <td>#NumberFormat((allLocCodeForLocationQry.locCntr/allLocCode.locationCount) * 100, '9.99')#%</td>
        <td>#allLocCodeForLocationQry.locCntr#</td>
      </tr>
     </cfoutput>
     </cfloop>
     <tr>
      <td><strong>Total</strong></td>
      <td></td>
      <td><cfoutput>#numberFormat(columnSum)#</cfoutput></td>
    </tr>
    </tbody>
    <!--- Total of All Sum of each column --->
</table>

试试这个。

每次循环查询时,将一个值(位置数)附加到列表中。

像这样:

<cfset myList = "">
<cfloop query="allLocCode">
<cfset myList = ListAppend(myList, locationCount, ',')>

<!---your other logic--->
</cfloop>

在你的循环结束时,你应该有一个数字列表,只要你的查询的记录数。

您可以使用我在 CFLib 上找到的这个旧函数将所有这些数字相加。

<cfscript>
function listSum(listStr)
{
  var delim = ",";
  if(ArrayLen(Arguments) GTE 2) 
    delim = Arguments[2];
  return ArraySum(ListToArray(listStr, delim));
}
</cfscript>

因此,例如,如果您的最终列表名为 myList 并且具有诸如 14, 100, 7 之类的值 - 您将写出:

<cfoutput>#listSum(myList)#</cfoutput>

并得到 121 的最终答案。

您的 columnSum 变量在您的 cfloop 中。将 <cfset columnSum = ArraySum(allLocCodeForLocationQry['locCntr'])> 行放在 cfloop 之外(之前或之后),您应该得到总计 334.

既然这是 sql 服务器,为什么不利用它使用 with 关键字的能力呢?大意是这样的:

with totalRecords as 
(select count(*) records
from etc),

groupedRecords as
(select someField, count(*) recordsForField
from etc
group by someField)

select whatevever
, (groupedRecords.recordsForField / totalRecords.records) * 100 percentage
from someTables
join groupedRecords on groupedRecords.someField = someTable.someField

where totalRecords.records > 0

然后您只需输出您的查询结果。