Map the record in the Branch1 table with records in the Email1 table and show the value for visits in the Email1 table as explained below:
Requirement:
- the value of 'visits ' for the 'campaign_name' 0001_RegOnly with 'day_id' 7th Nov 2021 in the branch1 table should be matched to the record in the email1 table which has the same campaign_name and has a send_date that is closest possible (less than or equal to) date to the day_id in the branch1 table. So, there are 3 records with the same campaign_name (0001_RegOnly) in the email table with dates 1st, 5th and 6th of Nov. So, the value of visits should be inserted to 5th nov record in the email table.
a) Incase there were records in the email table for the same campaign_name (0001_RegOnly), let's say for the date 8th of November instead of 6th of November, then the value should be assigned to the record with the same campaign name that has the date as 5th of November. And not 8th of Nov as 8th of Nov is greater than 7th of Nov.
b) Incase there were records in the email table for the same campaign name (0001_RegOnly), let's say for the date 7thof November along with 1st, 5th, and 6th of November, then the value should be assigned to the record with the same campaign name that has the date as 7th of November as it is the closest possible date, in this case equal (branch1.day_id is 7 and email1.send_date is 7 as well)
Condition:
- branch1.campaign_name = email1.campaign_name
- branch1.day_id >= email1.send_date
Tables:
SQL QUERY that I have used:
with CTE as
(
select campaign_name, send_date, lead (send_date) over (order by send_date) as nextdate
from email1
group by campaign_name, send_date
)
select a.campaign_name, a.send_date, sum(b.visits) as visits
from CTE a left join branch1 b
on b.day_id>a.send_date and b.day_id<a.nextdate
and a.campaign_name = b.campaign_name
group by a.send_date, a.campaign_name
order by send_date
;
Actual Output: SQL Query Output