tags:

views:

32

answers:

2

I'm currently developing a program that will generate reports based upon lead data. My issue is that I'm running 3 queries for something that I would like to only have to run one query for. For instance, I want to gather data for leads generated in the past day submission_date > (NOW() - INTERVAL 1 DAY) and I would like to find out how many total leads there were, and how many sold leads there were in that timeframe. (sold=1 / sold=0). The issue comes with the fact that this query is currently being done with 2 queries, one with WHEREsold= 1 and one with WHEREsold= 0. This is all well and good, but when I want to generate this data for the past day,week,month,year,and all time I will have to run 10 queries to obtain this data. I feel like there HAS to be a more efficient way of doing this. I know I can create a mySQL function for this, but I don't see how this could solve the problem. Thanks!!

+2  A: 

Why not GROUP BY sold so you get the totals for sold and not sold

Leslie
Awesome, that will solve the issue of sold vs not sold. Any way to do this for day,week,month,year?
Brendan
@Brendan: it might not be more efficient than separate queries, but you could create a temp table (call it 'cutoff_times') with the 5 cutoff values, and then do `main_table AS m JOIN cutoff_times AS t ON m.submission_date > t.cutoff_date`. This is a 'greater-than join' rather than the usual equi-join.
Jonathan Leffler
A: 

One way to do is to exploit the aggregate functions (usually SUM and COUNT help you the most in this situation) along with MySQL's IF() function.

For example, you could use a query such as:

SELECT 
  SUM(IF(sold = 1, sold, 0)) AS TotalSold, 
  SUM(IF(sold = 0, sold, 0)) AS TotalUnsold,
  SUM(IF(submission_date > (NOW() - INTERVAL 1 WEEK) 
    AND sold = 1, sold, 0) AS TotalSoldThisWeek
FROM ...
WHERE ...

The condition (e.g. sold = 1) could be as complex as you want by using AND and OR.

Disclamer: code wasn't tested, this was just provided as an example that should work with minor modifications.

Senseful
Awesome, I like that alternative better, and it should be applicable using submission_date > (NOW() - INTERVAL 1 DAY too
Brendan
See my updated code for an example of that.
Senseful
Thanks so much for all your help, made my life a LOT easier :)
Brendan
No problem. As you seem new to the community, I'll provide you with this advice: if there's an answer you like, consider, in addition to accepting it as the best answer, also clicking the up arrow to give the answerer some more rep.
Senseful