Ах, только с данными за один месяц в таблице и разложением подвыбора на CTE, чтобы увидеть, могу ли я увидеть шаблон. Я не вижу ничего .. и, таким образом, мне кажется, что вам нравится ваш SQL (мне)
with person_table as (
select column1 as month, column2 as movie, column3 as person_id, column4 as unique_visit_id
from values (1, 'a', 1, 1),
(1, 'b', 1, 2),
(1, 'b', 2, 3),
(1, 'a', 2, 4),
(1, 'c', 3, 5),
(1, 'd', 4, 6),
(1, 'a', 2, 7),
(1, 'c', 3, 8),
(1, 'a', 6, 9)
), weight_table as (
select column1 as person_id, column2 as weight
from values (1, 12), (2, 34), (3, 65), (4, 76), (999,999)
), dis_month_people as (
select distinct month, person_id
from person_table
), month_share as (
select month, sum(weight) as total_weight
from dis_month_people dp
join weight_table w on dp.person_id = w.person_id
group by 1
), dis_month_movie_people as (
select distinct month, movie, person_id
from person_table
)
select t.* --, weighted, total_weight
,t.weighted/m.total_weight as share
from (
select
a.month,
a.movie,
count(a.person_id) as raw,
sum(b.weight) as weighted
from dis_month_movie_people a
join weight_table b on a.person_id = b.person_id
group by 1,2
) AS t
join month_share m on t.month = m.month
order by 1,2;