如何计算列总和

问题描述 投票:1回答:3

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

<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>,意味着很多不相关的数据。这可能是什么错误?

coldfusion sum row cfml
3个回答
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年里,我没有使用过字体标签。除非处理依赖于它的某些遗留代码,否则不应使用字体标记。


16
投票

如果您的查询中有一列,并且您可以确保每个值都是数字,您还可以执行以下操作:

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

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


0
投票

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

<cfset theSum = ArraySum(ListToArray(ValueList(queryName.column))) />
© www.soinside.com 2019 - 2024. All rights reserved.