Skip to content

Commit

Permalink
Update Number of transactions per visit.sql
Browse files Browse the repository at this point in the history
  • Loading branch information
mrinal1704 authored Jul 5, 2020
1 parent 0b08ae0 commit d392039
Showing 1 changed file with 33 additions and 26 deletions.
59 changes: 33 additions & 26 deletions Hard/Number of transactions per visit.sql
Original file line number Diff line number Diff line change
Expand Up @@ -83,31 +83,38 @@
-- * For transactions_count >= 4, No customers visited the bank and did more than three transactions so we will stop at transactions_count = 3

-- Solution
with recursive t1 as(
(select visit_date, coalesce(num_visits,0) as num_visits, coalesce(num_trans,0) as num_trans
from
(select visit_date, user_id, count(*) as num_visits
from visits
group by 1, 2) a
left join
(select transaction_date, user_id, count(*) as num_trans
from transactions
group by 1, 2) b
on a.visit_date = b.transaction_date and a.user_id = b.user_id)),
WITH RECURSIVE t1 AS(
SELECT visit_date,
COALESCE(num_visits,0) as num_visits,
COALESCE(num_trans,0) as num_trans
FROM ((
SELECT visit_date, user_id, COUNT(*) as num_visits
FROM visits
GROUP BY 1, 2) AS a
LEFT JOIN
(
SELECT transaction_date,
user_id,
count(*) as num_trans
FROM transactions
GROUP BY 1, 2) AS b
ON a.visit_date = b.transaction_date and a.user_id = b.user_id)
),

t2 as(
select max(num_trans) as trans
from t1
union all
select trans-1 from t2
where trans>=1
)
t2 AS (
SELECT MAX(num_trans) as trans
FROM t1
UNION ALL
SELECT trans-1
FROM t2
WHERE trans >= 1)

select trans as transactions_count, coalesce(visits_count,0) as visits_count
from t2 left join
(select num_trans as transactions_count, coalesce(count(*),0) as visits_count
from t1
group by 1
order by 1) a
on a.transactions_count = t2.trans
order by 1
SELECT trans as transactions_count,
COALESCE(visits_count,0) as visits_count
FROM t2 LEFT JOIN (
SELECT num_trans as transactions_count, COALESCE(COUNT(*),0) as visits_count
FROM t1
GROUP BY 1
ORDER BY 1) AS a
ON a.transactions_count = t2.trans
ORDER BY 1

0 comments on commit d392039

Please sign in to comment.