これがあなたの質問に対する私の提案です。
まず、日付フィールドに基づいて週番号を見つける必要があったので、この質問の答えを使用しました:
SELECT WEEK(dateField, 5) -
WEEK(DATE_SUB(dateField, INTERVAL DAYOFMONTH(dateField) - 1 DAY), 5) + 1
読みやすくするために、これからは上記の結果を@weekと呼びます:)
次に、テーブルの1つだけから始めて、営業担当者が毎月何人の訪問者を獲得したかを確認しました。
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
この情報を取得したので、バイヤーにも同じものを使用して、次のようにこれら2つのサブクエリの結果を結合します。
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