I have a query that I am running multiple times for each day over a range. I would like to reduce this to a single query:
SELECT SUM(amount) AS all_time_revenue
FROM charges WHERE DATE(`charges`.`created_at`) <= '2015-03-01'
I'm running into a problem trying to convert this into a single query - I can't GROUP BY
"created_at" because I am capturing all charges before and on the date. (Not just on that date). Not sure if this is possible, but I'm sure if it is there is a genius on here that can solve it. Note: It would also be nice if I could return the myDate as well as the sum for each row.
Here is a complete example of what I'm doing:
$start_time = new DateTime('2016-08-01');
$end_time = new DateTime('2016-08-14');
$data = [];
for ($start_time; $start_time < $end_time; $start_time = $start_time->modify('+1 day')) {
$date = $start_time->format("Y-m-d");
$results = DB::SELECT("SELECT SUM(amount) AS all_time_revenue
FROM charges
WHERE `charges`.`created_at` <= ? AND `charges`.`sandbox`=0",
", [$date]);
$data[$date] = $results[0]->all_time_revenue;
}
So ideally I would like to run a single query that can work with a date range or a single date and number of days interval and have it spit out rows like:
row 1: ['2016-08-01', 4000.00]
row 2: ['2016-08-02', 4500.00]
...
row 14:['2016-08-14', 15000.00]