I have a database which stores the total cost of each customer on each date for a range of dates.
I'm trying to accomplish the following:- For each date in the range from x to y
- plot the average total costs among all customers for each date
- however, limit the average total cost calculations to customers who's average total_costs within dates x to y are > $50/day
Screenshot of the database:
Sample of "Dailies" database
I've attempted the above with the following query, but obtained inaccurate results (see images below). I've also attached a sample of the "dailies" table in which the query references.
SELECT dailies.date, dailies.cust_id, dailies.day_cost_total, dailies.date,
(SELECT avg(dailies.day_cost_total) FROM dailies WHERE dailies.day_cost_total > 50
AND dailies.date BETWEEN '2010-07-01' AND '2010-09-30' ) AS average_cost_total
FROM dailies
WHERE dailies.date BETWEEN '2010-07-01' AND '2010-09-30'
GROUP BY dailies.date ORDER BY dailies.date ASC
- SELECT dailies.date, dailies.cust_id, dailies.day_cost_total, dailies.date,
- (SELECT avg(dailies.day_cost_total) FROM dailies WHERE dailies.day_cost_total > 50
- AND dailies.date BETWEEN '2010-07-01' AND '2010-09-30' ) AS average_cost_total
- FROM dailies
- WHERE dailies.date BETWEEN '2010-07-01' AND '2010-09-30'
- GROUP BY dailies.date ORDER BY dailies.date ASC
Screenshot of results:
Results of above query.
I'm trying to avoid having to perform a MySQL call, store the data in a class/struct, then do the analysis in a script... I almost feel as if I need a loop within the query? Perhaps there is a more efficient way?
Thanks!