我指的是之前标记为正确答案的SO Coldfusion Calculate Sum Total (Loop? ),但该代码对我不起作用。
我正在尝试从几个领域创建一个总计。但我收到的错误是“未定义变量xxx”。这是因为我试图从循环中为所有记录附加值
<cfoutput>
<cfquery name="ActivityReceipts" dbtype="query">
SELECT
activity,
qty_approved,
location,
payment_amount,
shipping_cost,
handling_cost
FROM rc.RC1
WHERE id_number = '#Receipts.id_number#'
</cfquery>
<cfloop query="ActivityReceipts">
<tr>
<td style="text-align:left;">#ActivityReceipts.activity#</td>
<td style="text-align:left;">#ActivityReceipts.qty_approved#</td>
<td style="text-align:left;">#ActivityReceipts.location#</td>
<td style="text-align: right; padding-right: 80px;">#ActivityReceipts.payment_amount#</td>
</tr>
<cfset grandTotal = grandTotal + ( #ActivityReceipts.payment_amount# + #ActivityReceipts.handling_cost# + #ActivityReceipts.Shipping_cost# ) />
</cfloop>
<td>#grandTotal#</td>
</cfoutput>
请注意,如果我将grandTotal变量设置行更改为
<cfset grandTotal = ( #ActivityReceipts.payment_amount# + #ActivityReceipts.handling_cost# + #ActivityReceipts.Shipping_cost# ) />
它不会导致错误,但它也只会汇总最后一行,而不是所有这些。
答案 0 :(得分:5)
你需要在循环之前为grandtotal var设置默认值...
<cfset grandTotal = 0>
此外,如果您不打算输出或引用var,则无需输入井号。
<cfset grandTotal = grandTotal + ( ActivityReceipts.payment_amount + ActivityReceipts.handling_cost + ActivityReceipts.Shipping_cost ) />
答案 1 :(得分:4)
你必须像这样初始化grandTotal
:
<cfset grandTotal = 0>
<cfloop query="ActivityReceipts">
<tr>
<td style="text-align:left;">#ActivityReceipts.activity#</td>
<td style="text-align:left;">#ActivityReceipts.qty_approved#</td>
<td style="text-align:left;">#ActivityReceipts.location#</td>
<td style="text-align: right; padding-right: 80px;">
#ActivityReceipts.payment_amount#
</td>
</tr>
<cfset grandTotal = grandTotal + ( ActivityReceipts.payment_amount
+ ActivityReceipts.handling_cost
+ ActivityReceipts.Shipping_cost
) />
</cfloop>
答案 2 :(得分:3)
这是一种没有循环的方法。
grandTotal = ArraySum(ActivityReceipts["payment_amount"])
+ ArraySum(ActivityReceipts["handling_cost"])
+ ArraySum(ActivityReceipts["Shipping_cost"]);
答案 3 :(得分:2)
您必须先定义并初始化变量grandTotal
,然后才能执行<cfset grandTotal = grandTotal + ...
之类的语句。做一些像:
...
</cfquery>
<cfset grandTotal= 0>
<cfloop query="ActivityReceipts">
...
答案 4 :(得分:2)
在循环之前从<cfset grandtotal=0>
开始。由于你在循环中引用它并且没有初始化,所以你得到了未定义。