我正在尝试使用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>
答案 0 :(得分:2)
您的columnSum
变量位于cfloop
内。将<cfset columnSum = ArraySum(allLocCodeForLocationQry['locCntr'])>
行放在cfloop
之外(之前或之后),您应该得到334
的总计。
答案 1 :(得分:1)
试试这个。
每次循环查询时,都会将一个值(位置数)附加到列表中。
这样的事情:
<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
的最终答案。
答案 2 :(得分:1)
由于这是sql server,为什么不利用它使用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
然后您只需输出查询结果。