如何计算列总和

时间:2011-05-14 11:03:58

标签: coldfusion sum row cfml

之前我问过这样的问题,但没有收到任何好的答案,可能是因为代码太长或我的问题不清楚。这个时候我会努力做到最好:)到目前为止,我已经编写了代码来从表中查找行和,这很好用:

<cfloop list="#product_id_list#" index="product_index">
    <cfloop list="#month_list#" index="month_index">
        <cfoutput query="GET_SALES_TOTAL">
            <cfif AY eq month_index and product_id eq product_index>
                <cfloop list="#type_index#" index="tt_index">
                    <cfset 'alan_#tt_index#_#month_index#_#product_index#' = evaluate(tt_index)>
                </cfloop>
            </cfif>
        </cfoutput>
    </cfloop>
</cfloop>
<cfset 'total_#ii_index#_#p_index#'=evaluate('total_#ii_index#_#p_index#') + #evaluate('alan_#ii_index#_#ddd_other#_#p_index#')#>

现在我想找一个列总和。列总和的代码有效,但不正确。它计算最后一个产品的总和:

<cfloop list="#product_id_list#" index="product_index">
    <cfloop list="#month_list#" index="month_index">
        <cfoutput query="GET_SALES_TOTAL">
            <cfif AY eq month_index and product_id eq product_index>
                <cfloop list="#type_index#" index="tt_index">
                    <cfset 'alan2_#tt_index#_#month_index#_#product_index#' = evaluate(tt_index)>
                </cfloop>
            </cfif>
        </cfoutput>
    </cfloop>
</cfloop>
<cfset 'total2_#ddd_other#_#p_index#'=evaluate('total2_#ddd_other#_#p_index#') + #evaluate('alan2_#ii_index#_#ddd_other#_#p_index#')#>

行总和的输出:

<cfloop list="#product_id_list#" index="p_index">
    <cfloop list="#type_index#" index="kk_ind">
        <td align="center">
          <font color="##FF0000">#TLFormat(evaluate('total_#kk_ind#_#p_index#'),0)#</font>
        </td> 
    </cfloop>
</cfloop>

和列总和的输出:

<cfloop list="#month_list#" index="kk">
 <td align="center">
   <cfset satis_oran= evaluate('total2_#kk#_#p_index#')>
     #evaluate(satis_oran)#
 </td>
</cfloop>

我知道我没有按产品ID循环列输出,因为一旦我循环它,它会生成很多<td>,这意味着很多不相关的数据。这可能是什么错误?

3 个答案:

答案 0 :(得分:16)

如果您的查询中有一列,并且您可以确保每个值都是数字,那么您也可以这样做:

<cfset sum = arraySum(queryname['column'])>

如果遇到任何非数字值,它将导致错误,因此您可能需要在该字段周围放置一个coalesce语句,以确保将任何空值转换为零。

答案 1 :(得分:2)

这很难理解。

一些建议......

尝试在sql语句中执行此操作

您可以简单地使用GROUP语句来汇总所有这些值。有点像...

select productindex
    , datepart('yyyy', datecolumn) as year
    , datepart('mm', datecolumn) as month
    , sum(valcolumn) as valcolumnsum
from productinfo
group by productindex, datepart('yyyy', datecolumn), datepart('mm', datecolumn)

如果并非所有月份或产品实际上都在返回的查询中,那就没问题。几个月后你仍然可以循环使用产品。

请勿使用评估

据我所知,CF在飞行中实际编译非常慢。如果需要动态引用变量名,请使用范围和括号。如果您实际上正在保存要在以后评估的语句,则可能存在替代方案

请勿使用字体标记

在过去的6年里,我没有使用过字体标签。除非处理依赖于它的某些遗留代码,否则不应使用字体标记。

答案 2 :(得分:0)

根据表格列的数据类型,尝试使用旧版本的CF版本:

<cfset theSum = ArraySum(ListToArray(ValueList(queryName.column))) />