Monday, October 27, 2008

SQL Case Problem - Solved with an Alternative Query

Yes! I did it. I was able to have an alternative query (Thanks to paxi for the initial UNION idea). As you can see, the code is longer than the one I posted yesterday, but then it is able to display what I need... perfectly.

I have here 3 SELECT statements, 2 of which are under the main SELECT and are combined thru UNION.

To evaluate these 2 SELECT statements, the first one is for the debit while the other one is for the credit. You may notice that in the intended debit select, I added NULL AS CREDIT and in the credit select counterpart, I added NULL AS DEBIT. This is because the UNION syntax requires me to have the two SELECT statements return tables that are equivalent (Same column data types and order).

And the SQL Query:

SELECT ABS(debit) AS debit, ABS(credit) AS credit, title FROM
(

SELECT entry_account.balance AS debit, null AS credit, accounts.title, entry_account.entry_id
FROM (entry_account INNER JOIN accounts ON entry_account.account_id = accounts.id)
WHERE (accounts.normal_balance = 'D') AND (entry_account.balance >= 0) OR (accounts.normal_balance = 'C') AND (entry_account.balance < 0)

UNION

SELECT null AS debit, entry_account_1.balance AS credit, accounts_1.title, entry_account_1.entry_id
FROM (entry_account entry_account_1 INNER JOIN accounts accounts_1 ON entry_account_1.account_id = accounts_1.id)
WHERE (accounts_1.normal_balance = 'C') AND (entry_account_1.balance >= 0) OR (accounts_1.normal_balance = 'D') AND (entry_account_1.balance < 0)

) derivedtbl_1
WHERE (entry_id = ?)

sweet...

No comments: