我正在嘗試完成以下任務 - 我希望在每個按日曆周分組的客戶的網站上查看會話。下面是該查詢我到目前爲止做到這一點:MYSQL - 按周分組,同時顯示沒有數值的星期
SELECT o.name
, s.organization_id
, count(s.id) as num_of_sessions
, CONCAT(s.created_at, ' - ', s.created_at + INTERVAL 6 DAY) AS week
FROM triton.sessions s
, triton.organizations o
where o.id=s.organization_id
and s.organization_id in (17,19,20,21,24,25,26,27,29,31,32,33,34,25,36,37,38,39,40,41,43,44,45,46,47,48,49,50,51,52,53,56,57,58,59,60,62,69,70,72)
GROUP BY s.organization_id, WEEK(s.created_at)
ORDER BY o.name, WEEK(s.created_at);
這樣做的問題是,與凡客沒有一個網站的會話數週未與0報道 - 而不是周未報。這是一個問題,因爲我無法輕鬆將數據轉化爲Excel,併爲每個客戶的會話創建圖表。
要嘗試解決這個問題,我創建了一個臨時星期表值從1-52每個星期數量和嘗試的方法在這個環節上建議:Summarise by week, even for empty rows
的挑戰是當我做了左外加入,我失去了組織的團隊。
下面是幾個星期以前只是組工作SQL(由組織試圖組前):
select w.weeknum
, sess.club
, sess.organization_id
, count(sess.club) from weeks w
left outer
join (select o.name as club
, s.organization_id
, s.created_at
from sessions s
, organizations o
where s.organization_id in (17,19,20,21,24,25,26,27,29,31,32,33,34,25,36,37,38,39,40,41,43,44,45,46,47,48,49,50,51,52,53,56,57,58,59,60,62,69,70,72)
and o.id=s.organization_id
) sess
on (w.weeknum = extract(week from sess.created_at))
group by w.weeknum
上面的代碼只是返回52行(各1周),與計給我每週有多少次會話。
我現在想擴展上面的代碼來做上面的事情,但是每個組織。我應該找回52 * N行,其中N是組織的數量。我認爲這將會像將該組織添加到groupby聲明一樣簡單,但是它只是返回了幾周的會話(導致我從一開始就遇到了問題)。以下是查詢:
select w.weeknum
, sess.club
, sess.organization_id
, count(sess.club)
from weeks w
left outer
join (select o.name as club
, s.organization_id
, s.created_at
from sessions s
, organizations o
where s.organization_id in (17,19,20,21,24,25,26,27,29,31,32,33,34,25,36,37,38,39,40,41,43,44,45,46,47,48,49,50,51,52,53,56,57,58,59,60,62,69,70,72)
and o.id=s.organization_id
) sess
on (w.weeknum = extract(week from sess.created_at))
group by sess.club, w.weeknum
order by sess.club
有沒有人有任何其他建議,我可以實現我的目標?基本上,對於我的每一位客戶,我希望能夠按周查看會話列表(即使他們在特定的一週內沒有會話)。
我想你會得到更好的迴應,如果你縮短你的te xt並格式化您的代碼 –