我有一个SQL查询,我在一个看起来像这样的mysql数据库上运行......
$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/>';
我想要做的是返回前7天每个值的计数,所以我可以得到这样的结果......
value | 01/01/2014 | 01/01/2014 | 01/01/2014
--------------------------------------------------
AA01 34 23 12
BR65 3 65 65
YR76 45 12 65
这是我之后需要用php函数做的事情,还是可以用SQL查询本身来完成?
答案 0 :(得分:1)
这个应该做的工作
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