Adding the values in a database query column in ColdFusion

The following example shows how you can get the average value and sum for a database query column in ColdFusion using the valueList(), listToArray(), arraySum(), and arrayAvg() functions.

<cfquery name="getArtPrices" datasource="cfartgallery" maxRows="5">
    SELECT A.PRICE
    FROM ART A
</cfquery>
 
<cfset priceList = valueList(getArtPrices.price) />
<cfset priceArr = listToArray(priceList) />
 
<cfoutput>
list: #priceList#<br/>
sum: #numberFormat(arraySum(priceArr))#<br/>
avg: #numberFormat(arrayAvg(priceArr))#<br/>
</cfoutput>

The previous example outputs the following text:

list: 10000,13900,12500,11100,13550
sum: 61,050
avg: 12,210

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>