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.
It hasn't been mentioned yet and would not be as efficient as a single select BUT as a solution you could use a
UNION
and group by your own static identifier (date range group) such as:This way would at least yield a single database request and not a loop in your code.
See updated Fiddle here: http://sqlfiddle.com/#!15/9ce0f/5
This will return all the month ranges' sum between a given date and today.
Tuples output - SQL Fiddle
Array output. Does not work on SQL Fiddle but works in my desktop.
I am coming from oracle PL/ SQL back ground. In my opinion you can use below query to use it. My understanding is that if any transaction is happening on 19-NOV-2013 1.00 AM is always going to be in 19 Nov to 20 Nov bucket so We should not worry about range I have created below query. I hope so it will help you.
I worked on the following code. It uses an XML file. The file or string contains the date ranges you need to sumarize. The Stored Procedure will return a table with the totals per specific range.
The parametrized query will look like the following one.
The first code was tested using fake data and it works properly. You need to make the required adjustments to types and names to the SP columns and variable types in accordance to your tables definition.
The idea of this approach is being able to report any information in the way you need it. You can also pass additional parameters via XML attributes. Check more info of OPEN XML on MSDN website
Hope it helps