Subject Re: [firebird-support] Little complicated SQL request from guru
Author Svein Erling Tysvaer
Sorry, I forgot that the remaining debt could be bigger than the current
price, and noticed that I'd reused the H4 alias:

SELECT C.NAME, H.ORDER_NO, H.CREDIT,
CASE WHEN 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)) THEN
(SELECT SUM(H6.CREDIT) FROM HISTORY H6
WHERE H6.CUSTOMERID = H.CUSTOMERID
AND H6.HISTORY_DATE <= H.HISTORY_DATE) -
(SELECT SUM(H7.DEBIT) FROM HISTORY H7
WHERE H7.CUSTOMERID = H.CUSTOMERID)
ELSE H.CREDIT END
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(H5.DEBIT) FROM HISTORY H5
WHERE H5.CUSTOMERID = H.CUSTOMERID)

HTH,
Set
> 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)