I'm trying to accomplish the following - I want to see the session on my website per customer grouped by calendar week. Here is the query i have so far to accomplish this:
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);
The issue with this is that weeks with where a customer did not have a website session aren't reported with a 0 - instead that week is not reported. This is an issue as I can't take the data into excel easily and create graphs for each customer's sessions.
To attempt to resolve this issue, I created a temp weeks table with values from 1-52 for each week number and attempted the approach suggested in this link: Summarise by week, even for empty rows
The challenge is when I do a left outer join, I lose the group by for organizations.
Here is a working SQL used to just group by weeks (before attempting to group by organization):
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
The above code just returns 52 rows (1 for each week), with the count giving me how many sessions in each week.
I now want to extend the above code to do the above but per organization. I should get back 52 * N rows where N is the number of organizations. I thought this would be as easy as adding the organization to the groupby statement, but it then only returned the weeks that had sesssions (resulting in the problem I had from the start). Here is the query:
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
Does anybody have any other suggestions where I can accomplish my goals? Essentially for every one of my customers, I want to see a list of sessions by week (even if they had no session in a particular week).