I have two tables and I want to merge them.
Fiddle here: http://sqlfiddle.com/#!17/999d0
Result
table is what I expect to get. Table utm
is a source-main table and table report
contains data for utm
rows. What I need:
- Take id and utm_ from
utm
table and add stats from tablereport
with proper granulation.
Example
In table utm
I’ve a row: (24611609, 'myTarget', 'Media', 'Social', NULL, NULL)
and in table report I’ve 2 rows:
(24611609, '2022-08-01', 200, 150, 15, 'myTarget', 'Media', 'Social', 'premium', 'subcribe'),
(24611609, '2022-08-01', 25, 10, 1, 'myTarget', 'Media', 'Social', 'free', 'subcribe')
Common is: 'myTarget', 'Media', 'Social'
Proper granularity level is id, utm_campaign, utm_source, utm_medium
, so I need to SUM and GROUP two rows by these keys. So for this I need something like this:
SELECT
utm.row_id AS id,
utm.utm_campaign,
utm.utm_source,
utm.utm_medium,
utm.utm_content,
utm.utm_term,
report.date_of_visit,
sum(report.sessions) as sessions,
sum(report.pageviews) as pageviews,
sum(report.bounces) as bounces
FROM utm
inner join report on utm.row_id = report.id and utm.utm_campaign = report.utm_campaign and utm.utm_source = report.utm_source and utm.utm_medium = report.utm_medium
group by utm.row_id,
utm.utm_campaign,
utm.utm_source,
utm.utm_medium,
utm.utm_content,
utm.utm_term,
report.date_of_visit
I don’t know how to deal with all possible granularity combinations. My idea was just use diffrent JOINS variations and merge results with UNION like:
join on id, utm_campaign
union
...
join on id, utm_campaign, utm_medium
union
...
join on id, utm_campaign, utm_source
...
But it’s really stupid, I should create > 1000 unions and joins.
Any tips?
2
Answers
Enjoy
Fiddle
A more strightforward solution 🙂
Fiddle