Ich versuche, die Summe einer Spalte mit ColdFusion und MS Sql zu berechnen.CF Abrufen der Summe einer Spalte in einer Datenbankabfrage
Will mir bitte jemand sagen, was ich übersehe? Meine Summe für die Standortgesamtmenge macht nicht die Summe der Spalte, sondern nimmt nur die letzte Zahl in dieser Spalte. Wo gehe ich falsch?
<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>
Sieht so aus, als ob Sie COUNT() in SQL verwenden können ... haben Sie SUM() versucht? – TRose
Ich denke, vielleicht habe ich das in die falsche Richtung gesehen. Mein erster Instinkt besteht immer darin, vor der Verwendung von ColdFusion-Variablen mathematisch zu arbeiten und Daten in der Abfrage selbst zu ändern, aber das ist hier nicht ratsam. Schau dir meine Antwort unten an - ich denke, es wird für dich funktionieren. – TRose