LC 1336. Number of Transactions per Visit

link

 

select t3.id as transactions_count, if(t5.cnt is null,0,t5.vcnt) as visits_count from 
(
select t0.id from (
select @num:=@num+1 as id from (select @num:=-1) p, Transactions 
union
select 0 as id    # Transactions maybe null 
)t0
join 
(
select max(cnt) as mx from
(
select v.user_id, v.visit_date, count(t.amount) as cnt
    from Visits v left join Transactions t
    on v.user_id=t.user_id and v.visit_date=t.transaction_date
    group by v.user_id, v.visit_date 
)t1
)t2 where t0.id<=t2.mx
)t3    # t3: left column 0--max
left join 
(
select cnt, count(*) as vcnt from
(
select v.user_id, v.visit_date, count(t.amount) as cnt
    from Visits v left join Transactions t
    on v.user_id=t.user_id and v.visit_date=t.transaction_date
    group by v.user_id, v.visit_date 
)t4 group by cnt
)t5 on t3.id=t5.cnt
原文地址:https://www.cnblogs.com/FEIIEF/p/12421934.html