forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-transactions-per-visit.sql
31 lines (30 loc) · 1.47 KB
/
number-of-transactions-per-visit.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Time: O(m + n)
# Space: O(m + n)
SELECT seq.transactions_count AS transactions_count,
Ifnull(v.visits_count, 0) AS visits_count
FROM (SELECT @count := CAST(@count + 1 AS SIGNED) AS transactions_count
FROM (SELECT @count := -1, @max_count := Ifnull(Max(count), 0)
FROM (SELECT Count(1) AS count
FROM transactions
GROUP BY user_id,
transaction_date
ORDER BY NULL) AS tmp) AS c
CROSS JOIN (SELECT user_id
FROM visits
UNION ALL
SELECT user_id
FROM transactions) AS m_n
WHERE @count < @max_count
) AS seq
LEFT JOIN (SELECT transactions_count,
Count(1) AS visits_Count
FROM (SELECT Count(transaction_date) AS transactions_count
FROM visits AS v
LEFT JOIN transactions AS t
ON v.user_id = t.user_id
AND visit_date = transaction_date
GROUP BY v.user_id,
visit_date
ORDER BY NULL) AS visits_count
GROUP BY transactions_count) AS v
ON seq.transactions_count = v.transactions_count