I have the following query:
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" BETWEEN '2013-12-20' AND '2014-01-19');
What that does is adds up all the "fees" that occurred between those two dates. Great. Works fine.
The problem is that I almost always need those fees for hundreds of date ranges at a time, which amounts to me running that same query hundreds of times. Not efficient.
But is there some way to condense this into a single query for all the date ranges?
For instance, I'd be calling SUM
for a series of ranges like this:
2013-12-20 to 2014-01-19
2013-12-21 to 2014-01-20
2013-12-22 to 2014-01-21
2013-12-23 to 2014-01-22
2013-12-24 to 2014-01-23
...so on and so on
I need to output the sum of fees collected in each date range (and ultimately need that in an array).
So, any ideas on a way to handle that and reduce database transactions?
FWIW, this is on Postgres inside a Rails app.
Well coming from a SQL Server background I would change your where clause to
Just be sure you have a good index on those dates! :)
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:
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:
and then change your main query to:
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:
But for this you have to create the SQL directly in the client application (ej. DAO)
Hope this helps.
Assuming I understand your request correctly I think what you need is something along these lines:
This should return you all the periods you're interested in in one single resultset. Since the query is 'generated' on the fly in your front-end you can add as many rows to the periods part as you want.
Edit: with some trial and error I managed to get it working [in sqlFiddle][1] and updated the syntax above accordingly.
Here's a untested procedure you can used.
Then call the procedure with your range date.
Here is link to SQL Fiddle Where I tested it: http://sqlfiddle.com/#!10/535ac/11/0
Try this: