I want to calculate the SUM of a CASE condition where one of the conditions uses a correlated subquery to find the results but i'm stuck with the syntax.
Here is a sample of the query that i created until now but with errors:
Updated
SELECT t1.account,
t1.date
SUM(CASE WHEN condition1 THEN t1.amount
WHEN condition2 THEN (select sum(t2.amount) from t2 where t2.account = t1.account and t2.date = t1.date)
ELSE 0 END) as total
FROM t1
GROUP BY t1.account, t1.date
The above query returns wrong results when the output of the subquery are multiple records. In a nutshell the result of condition2 is sum(t2.amount) * (number of records).
I tried removing the sum() function from the subquery but since it can fetch multiple records i still got an error.
I believe it can be done somehow but i'm stuck.
Can anyone suggest something.
Btw i'm using Postgresql 9.4