I have the following query:
SELECT
SUM(\"balance_transactions\".\"fee\") AS sum_id
FROM \"balance_transactions\"
JOIN charges ON balance_transactions
if i understand well you want to reutilize the date query. For this the part of the query that can be reutilized is the daily part. I mean:
SELECT
SUM("balance_transactions"."fee") AS sum_id
FROM "balance_transactions"
JOIN charges ON balance_transactions.source = charges.balance_id
WHERE "balance_transactions"."account_id" = 6
AND (balance_transactions.type = 'charge'
AND charges.refunded = false
AND charges.invoice IS NOT NULL)
AND ("balance_transactions"."created" = 'yyyy-mm-dd');
Assuming that your "created" field is just date and not timestamp, and if the data of past days doesn't change, you can dump this query to a table:
insert into sum_table
SELECT
"balance_transactions"."created" balance_created
SUM("balance_transactions"."fee") AS balance_fee
FROM "balance_transactions"
JOIN charges ON balance_transactions.source = charges.balance_id
WHERE "balance_transactions"."account_id" = 6
AND (balance_transactions.type = 'charge'
AND charges.refunded = false
AND charges.invoice IS NOT NULL)
group by "balance_transactions"."created"
;
and then change your main query to:
SELECT
SUM(balance_fee) AS sum_id
FROM sum_table where balance_created between ('2013-12-20' AND '2014-01-19');
Another optimization is to eliminate the between because usually it does not uses indexes, and if you have lots of different dates it can be slow.
Better this way:
SELECT
SUM(balance_fee) AS sum_id
FROM sum_table where balance_created in ('2013-12-20', '2013-12-21', '2013-12-22' ... '2014-01-19');
But for this you have to create the SQL directly in the client application (ej. DAO)
Hope this helps.