I have a simple query that pulls a list of records by their ID:
<cfquery name="resTotals" datasource="#datasource#">
SELECT ticket_id
FROM closed_tickets
WHERE YEAR(closed_date) = '2017'
AND ticket_type = 'residential'
</cfquery>
I am then trying to loop through those ID's in another query of a different table so I can check for the existence of a payment record. The goal is to then total up all the payment records find to get a total amount in dollar of payments.
I have this query to do that but it is throwing an error: Can't cast String [99.00] to a value of type [Array]
<cfloop query="resTotals">
<cfquery name="resPaymentTotals" datasource="#datasource#">
SELECT payment_amount
FROM payments
WHERE ticket_id = #resTotals.ticket_id#
</cfquery>
</cfloop>
Amount of Sales: $ #ArraySum(resPaymentTotals.payment_amount)#
What am I doing wrong? Am I on the right track?
As the error message suggests, you're using a string where an array is expected. In other words, ArraySum() expects an array, but you're passing in a string. Technically a query column is an array behind the scenes, but apparently ArraySum isn't designed to treat it that way. In this case CF treats
resPaymentTotals.payment_amount
as shortcut for the 1st value in the payment_amount column, which is a simple value, not an array.While you could make the current code work, querying within looping is very inefficient. What you really need is a JOIN, not a loop. To calculate the total - per ticket_id - in a single query:
If you want the overall total for all tickets, just omit ticket_id from the SELECT.
I would just use one query, and like Ageax said, just
JOIN
the tables. When you do this, you'll have to account for the duplicated primary table rows that you may get.For the SQL:
SQL Fiddle
This Setup is assuming MS SQL Server. It can be ignored.
The Query:
This Gives You:
So now I assume you'll be doing something with those ticket_IDs; probably looping through them. Note: I'd rename the query to be descriptive of the data you're returning. We changed its definition.
Note
ticket_id
3 and 4, and differences between theirtotalPamentAmount
andbadPaymentAmount
. Both have aNULL
value for a payment: 3 has an explicitNULL
and 4 has an implicitNULL
since there are no matching rows. Normally, if you add1+NULL
, you'll getNULL
, sinceNULL
has no value; you want1+0
instead. SQLsum()
will account for the explicitNULL
, but not for an implicitNULL
. For the implicitNULL
, we can usecoalesce()
to return the first non-NULL
value. Then we can sub0
forNULL
and do math fortotalPaymentAmount
.