Subject Re: [firebird-support] Little complicated SQL request from guru
Author Svein Erling Tysvaer
SQL request? I'd say this sounds like something that most "Firebirdies"
would prefer to solve with a stored procedure. Though it can be done
with plain SQL, at least if you don't have a lot of rows for each
customer (a stored procedure can do things sequentially, plain SQL has
to repeat the calculation for each row and it gets slow if e.g. 10000
customers place 10000 orders each).

SELECT C.NAME, H.ORDER_NO, H.CREDIT,
(SELECT SUM(H2.CREDIT) FROM HISTORY H2
WHERE H2.CUSTOMERID = H.CUSTOMERID
AND H2.HISTORY_DATE <= H.HISTORY_DATE) -
(SELECT SUM(H3.DEBIT) FROM HISTORY H3
WHERE H3.CUSTOMERID = H.CUSTOMERID) as REMAINING_DEBT
FROM CUSTOMERS C
JOIN HISTORY H ON C.CUSTOMERID = H.CUSTOMERID
WHERE (SELECT SUM(H4.CREDIT) FROM HISTORY H4
WHERE H4.CUSTOMERID = H.CUSTOMERID
AND H4.HISTORY_DATE <= H.HISTORY_DATE) >
(SELECT SUM(H4.DEBIT) FROM HISTORY H4
WHERE H4.CUSTOMERID = H.CUSTOMERID)

Note that I in this solution have assumed that customers never place
more than one order per day (you would need to add more logic to order
the orders placed on the same day).

HTH,
Set

majstoru wrote:
> Hi,
>
> I have two tables:
>
> Customers (id, name)
> History (cust_id, descript, in_money, out_money)
>
> Here is a sample data:
>
> Customers:
> 1 Cust_Name1
> 2 Cust_Name2
> 3 Cust_Name3
>
> History
> 1 Order No 01 0.00 100.00
> 1 Order No 02 0.00 150.00
> 1 Order No 03 0.00 180.00
> 2 Order No 04 0.00 200.00
> 2 Order No 05 0.00 250.00
> 2 BankReport 1 200.00 0.00
> 1 BankReport 2 150.00 0.00
>
> and I need SQL statement to get all order documents that are not
> complet payed.
>
> Cust_Name1 Order No 02 150.00 50.00
> Cust_Name1 Order No 03 180.00 180.00
> Cust_Name2 Order No 05 250.00 250.00
>
> Last column is value which is represen the unclosed order by payment!
>
> If I wasn't complicated in my description that is my SQL problem!
>
> Thanks in advance...