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...
Monday, October 27, 2008
Saturday, October 25, 2008
SQL Case Problem
SELECT (CASE WHEN entry_account.balance > 0 THEN entry_account.balance ELSE null END) AS debit, accounts.title
FROM ((entry_account INNER JOIN
accounts ON entry_account.account_id = accounts.id) INNER JOIN
entry ON entry_account.entry_id = entry.id)
WHERE (entry.id = ?)
Basically, the above code simply wants to put a value in the debit column if entry_account.balance is > 0 else NULL is appended. This is not exactly what my business logic is but I just have to make it simpler to actually get myself familiarized with the CASE syntax.
The problem is, it just doesn't work. I browsed a couple of code snippets and all of them don't give my an idea why my code is wrong.
Have to sleep now, I might just get the answer tomorrow.
FROM ((entry_account INNER JOIN
accounts ON entry_account.account_id = accounts.id) INNER JOIN
entry ON entry_account.entry_id = entry.id)
WHERE (entry.id = ?)
Basically, the above code simply wants to put a value in the debit column if entry_account.balance is > 0 else NULL is appended. This is not exactly what my business logic is but I just have to make it simpler to actually get myself familiarized with the CASE syntax.
The problem is, it just doesn't work. I browsed a couple of code snippets and all of them don't give my an idea why my code is wrong.
Have to sleep now, I might just get the answer tomorrow.
Subscribe to:
Posts (Atom)
