Subject Re: [firebird-support] help on query
Author sugi
> Please help me to write a SELECT statment which
> returns
> the account_id of the amount which is appearing as a
> total to the multiple entries ( account_id 522 and
> 525 in this example).

Something like this should work :
...
select t1.journal_no, t1.account_id
from table t1
where
(t1.debit =
(select max(abs(t2.debit - t2.credit))
from table t2
where t1.journal_no = t2.journal_no)
)
or
(t1.credit =
(select max(abs(t2.debit - t2.credit))
from table t2
where t1.journal_no = t2.journal_no)
);
...

but you'd need to declare the abs() udf function first :
...
DECLARE EXTERNAL FUNCTION abs
DOUBLE PRECISION
RETURNS DOUBLE PRECISION BY VALUE
ENTRY_POINT 'IB_UDF_abs' MODULE_NAME 'ib_udf';
...

Btw, if you cannot use the UDF for whatever reason, it can be simulated
using the CASE statement.

Two cases where the above approach will fail :
1. journal_no | account_id | debit | credit
01 | 001 | 100 | 0
01 | 002 | 0 | 100
The above SELECT returns both of these records. (Can be worked around,
though...)

2. journal_no | account_id | debit | credit
01 | 001 | 100 | 0
01 | 002 | 0 | 200
01 | 003 | 250 | 0
01 | 004 | 0 | 50
Strange, i know, but i've seen these popping up in a production
database. In this case, none of the entries are equal to the total, so
NONE of the entries are returned. Depending on how you want to handle
this, the above might or might not be usable.

When tested on Firebird1.5 RC7 with a table of 150.000 records, the
performance is not bad at all, but I'm wondering if the query can be
optimized further. I don't particularly like the duplication of the
identical select MAX()s. I'm wondering whether Firebird is smart enough
to reuse the MAX() value from the first run instead of executing it
twice for each record.

Salam,
sugi.