这是我对您查询的建议。
首先,我需要根据日期字段找出周数,所以我在这个问题中使用了答案:
SELECT WEEK(dateField, 5) -
WEEK(DATE_SUB(dateField, INTERVAL DAYOFMONTH(dateField) - 1 DAY), 5) + 1
从现在开始,我会将上述结果称为@week,以使内容更具可读性:)
然后,我从一张表开始,试图查看销售代表每个月有多少访客:
select rep,
, SUM(CASE @week WHEN 1 THEN 1 ELSE 0 END) as Week1
, SUM(CASE @week WHEN 2 THEN 1 ELSE 0 END) as Week2
, SUM(CASE @week WHEN 3 THEN 1 ELSE 0 END) as Week3
, SUM(CASE @week WHEN 4 THEN 1 ELSE 0 END) as Week4
, COUNT(*) as Total
from visitors
group by rep
既然我们得到了这个信息,我们将对买家使用相同的信息,然后加入这两个子查询的结果,如下所示:
select v.rep
, v.Week1 , b.Week1
, v.Week2 , b.Week2
, v.Week3 , b.Week3
, v.Week4 , b.Week4
, v.Total, b.Total
from (
select rep,
, SUM(CASE @week WHEN 1 THEN 1 ELSE 0 END) as Week1
, SUM(CASE @week WHEN 2 THEN 1 ELSE 0 END) as Week2
, SUM(CASE @week WHEN 3 THEN 1 ELSE 0 END) as Week3
, SUM(CASE @week WHEN 4 THEN 1 ELSE 0 END) as Week4
, COUNT(*) as Total
from visitors
group by rep) as v
left join (select rep,
, SUM(CASE @week WHEN 1 THEN 1 ELSE 0 END) as Week1
, SUM(CASE @week WHEN 2 THEN 1 ELSE 0 END) as Week2
, SUM(CASE @week WHEN 3 THEN 1 ELSE 0 END) as Week3
, SUM(CASE @week WHEN 4 THEN 1 ELSE 0 END) as Week4
, COUNT(*) as Total
from visitors
group by rep) as b on v.rep = b.rep
这应该是你要找的!
这是根据您的情况更新的与上面相同的代码:
select v.rep
, v.Week1 , b.Week1
, v.Week2 , b.Week2
, v.Week3 , b.Week3
, v.Week4 , b.Week4
, v.Total, b.Total
from (
select rep
, SUM(CASE WEEK(the_date, 5) -
WEEK(DATE_SUB(the_date, INTERVAL DAYOFMONTH(the_date) - 1 DAY), 5) + 1
WHEN 1 THEN 1 ELSE 0 END) as Week1
, SUM(CASE WEEK(the_date, 5) -
WEEK(DATE_SUB(the_date, INTERVAL DAYOFMONTH(the_date) - 1 DAY), 5) + 1
WHEN 2 THEN 1 ELSE 0 END) as Week2
, SUM(CASE WEEK(the_date, 5) -
WEEK(DATE_SUB(the_date, INTERVAL DAYOFMONTH(the_date) - 1 DAY), 5) + 1
WHEN 3 THEN 1 ELSE 0 END) as Week3
, SUM(CASE WEEK(the_date, 5) -
WEEK(DATE_SUB(the_date, INTERVAL DAYOFMONTH(the_date) - 1 DAY), 5) + 1
WHEN 4 THEN 1 ELSE 0 END) as Week4
, COUNT(*) as Total
from visitors
where sales_rep = '$sales_rep' AND date('Y-m') = $'chosen_month'
group by rep ) as v
left join (
select rep
, SUM(CASE WEEK(the_date, 5) -
WEEK(DATE_SUB(the_date, INTERVAL DAYOFMONTH(the_date) - 1 DAY), 5) + 1
WHEN 1 THEN 1 ELSE 0 END) as Week1
, SUM(CASE WEEK(the_date, 5) -
WEEK(DATE_SUB(the_date, INTERVAL DAYOFMONTH(the_date) - 1 DAY), 5) + 1
WHEN 2 THEN 1 ELSE 0 END) as Week2
, SUM(CASE WEEK(the_date, 5) -
WEEK(DATE_SUB(the_date, INTERVAL DAYOFMONTH(the_date) - 1 DAY), 5) + 1
WHEN 3 THEN 1 ELSE 0 END) as Week3
, SUM(CASE WEEK(the_date, 5) -
WEEK(DATE_SUB(the_date, INTERVAL DAYOFMONTH(the_date) - 1 DAY), 5) + 1
WHEN 4 THEN 1 ELSE 0 END) as Week4
, COUNT(*) as Total
from buyers
where marketing_type = "URL" AND sales_rep = '$sales_rep' AND date('Y-m') = $'chosen_month'
group by rep) as b on v.rep = b.rep