0

I have a SQL query I am running on a mysql database that looks like this...

    $count0 = $wpdb->get_results("

 SELECT *, COUNT(*) as TotalValueCount 
   FROM
   wp_rg_lead
   INNER JOIN wp_rg_lead_detail ON
   wp_rg_lead.id=wp_rg_lead_detail.lead_id
   WHERE wp_rg_lead.form_id = '46'
   AND  cast(date_created as date) >= current_date - interval '7' day
   AND field_number = '18'
   GROUP BY value
            ");

    foreach ( $count0 as $page ) {
   echo $repid_field . ' - ' . $page->form_id . ' -  ' . $page->value .  ' - ' . $page->lead_id . ' - ' . $page->date_created.' - ' . $page->TotalValueCount. '<br/>';

What I want to do with this however is return a count for each value for each of the previous 7 days, so I can get results something like this...

value  |  01/01/2014  |  01/01/2014  |  01/01/2014
--------------------------------------------------
AA01         34              23            12
BR65         3               65            65
YR76         45              12            65

Is this something I would need to do with the php function afterwards or can this be done with the SQL query itself?

2
  • 1
    Imho, you should not try to get the expected output within mysql itself. Get the desired data grouping by value and date, and then use/format it with php/html. Commented Dec 2, 2014 at 8:38
  • That is the way I was leaning myself. Thanks for the advice Commented Dec 2, 2014 at 8:45

1 Answer 1

1

this one should do the job

SELECT   value, 
        sum(case 
                when cast(date_created as date) = current_date - interval '7' day 
                then 1 else 0 end
            ) d7,
        ...
        sum(case 
                when cast(date_created as date) = current_date - interval '1' day 
                then 1 else 0 end
            ) d1
FROM  wp_rg_lead
INNER JOIN wp_rg_lead_detail ON
wp_rg_lead.id=wp_rg_lead_detail.lead_id
WHERE wp_rg_lead.form_id = '46'
AND  cast(date_created as date) >= current_date - interval '7' day
AND field_number = '18'
GROUP BY value
Sign up to request clarification or add additional context in comments.

2 Comments

The date_created field is formatted like this '2014-12-01 14:23:00' - Is there a way to replace the d1,d2,d3 etc.. with the date itself?
I think the answer is rather no. I'd better leave such formating for php/html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.