I want to list positive and negative bank_transfers
from my DB. To do so I’m using below query:
SELECT bank_transfers.date AS day, CAST(SUM(CASE WHEN bank_transfers.amount_cents < 0 THEN bank_transfers.amount_cents END)) AS sum_expenses, CAST(SUM(CASE WHEN bank_transfers.amount_cents > 0 THEN bank_transfers.amount_cents END)) AS sum_revenue FROM bank_transfers JOIN customers ON customers.id = bank_transfers.customer_id WHERE customers.id = 1 AND bank_transfers.date < '2020-11-26' AND bank_transfers.date >= '2020-08-26' GROUP BY DAY
But it gives me an error syntax error at or near ")"
. I guess it comes from the CAST
so where should I close the parentheses?
Advertisement
Answer
You don’t even need those casts. You’re not casting into any type (unless sum_expenses
and sum_revenue
are your custom types).
Edit: If you want to cast to integer:
SELECT bank_transfers.date AS day, SUM(CASE WHEN bank_transfers.amount_cents < 0 THEN bank_transfers.amount_cents END)::integer AS sum_expenses, SUM(CASE WHEN bank_transfers.amount_cents > 0 THEN bank_transfers.amount_cents END)::integer AS sum_revenue FROM bank_transfers JOIN customers ON customers.id = bank_transfers.customer_id WHERE customers.id = 1 AND bank_transfers.date < '2020-11-26' AND bank_transfers.date >= '2020-08-26' GROUP BY DAY
Or use cast(... as integer)
.