I want to summarize some COUNT data by week. The week starts on Sunday. The query must account for weeks where the COUNT is 0. The counts are on two dates. A referral date and the service date. All I want to do is count the number of referrals for each week and how many service dates there are in the same week. These two COUNTS are not linked. A referral may come in 1 week but the service get done another week.
My attempt: 1) I created a calendar table with a entry for each day for the period I am working. The date entries cover more than the period being used. 2) I have a field in my Select that summarizes by 'Week Beginning' 3) I have COUNT fields on each of the date fields (Referral, Visits). Note that I use Distinct because there are multiple service codes for a visit but I only need to count them as 1.
Here is the code:
select
STR_TO_DATE(DATE_FORMAT(FROM_DAYS(TO_DAYS(calendar.datefield) - MOD(TO_DAYS(calendar.datefield) -1, 7)),'%m/%d/%Y'), '%m/%d/%Y' ) AS `Week Beginning`,
COUNT(DISTINCT opsData.`Patient Last Name`, opsData.`Patient First Name`, opsData.Discipline, opsData.`Referral Date`) as `Referrals`,
COUNT(DISTINCT opsData.`Patient Last Name`, opsData.`Patient First Name`, opsData.`Date of Service`) as Visits
from opsdata RIGHT JOIN calendar ON (DATE(opsData.`Referral Date`) = calendar.datefield)
where (calendar.datefield BETWEEN (SELECT MIN(DATE(opsData.`Referral Date`)) FROM opsdata) AND (SELECT MAX(DATE(opsData.`Referral Date`)) FROM opsdata))
group by `Week Beginning`
order by `Week Beginning` ASC
The problem i'm having is that I can only get 1 of the COUNTS to be accurate at a time based on the RIGHT JOIN. If I use DATE(opsData.Referral Date
) then the Referral COUNT is correct and the Visits is wrong. If I use DATE(opsData.Date of Service
) then the Visits is correct and the Referral COUNT is wrong.
Any ideas?