forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user-purchase-platform.sql
54 lines (53 loc) · 1.76 KB
/
user-purchase-platform.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# Time: O(n)
# Space: O(n)
SELECT t1.spend_date,
'both' AS platform,
Sum(Ifnull(t.sum_amount, 0)) AS total_amount,
Count(t.user_id) AS total_users
FROM (SELECT spend_date,
user_id,
Sum(amount) AS sum_amount
FROM spending
GROUP BY spend_date,
user_id
HAVING Count(platform) = 2) AS t
RIGHT JOIN (SELECT DISTINCT spend_date
FROM spending) AS t1
ON t.spend_date = t1.spend_date
GROUP BY t1.spend_date
UNION
SELECT t2.spend_date,
'mobile' AS platform,
Sum(Ifnull(t.amount, 0)) AS total_amount,
Count(t.user_id) AS total_users
FROM (SELECT spend_date,
user_id,
platform,
amount
FROM spending
GROUP BY spend_date,
user_id
HAVING Count(platform) < 2) AS t
RIGHT JOIN (SELECT DISTINCT spend_date
FROM spending) AS t2
ON t.spend_date = t2.spend_date
AND t.platform = 'mobile'
GROUP BY t2.spend_date
UNION
SELECT t3.spend_date,
'desktop' AS platform,
Sum(Ifnull(t.amount, 0)) AS total_amount,
Count(t.user_id) AS total_users
FROM (SELECT spend_date,
user_id,
platform,
amount
FROM spending
GROUP BY spend_date,
user_id
HAVING Count(platform) < 2) AS t
RIGHT JOIN (SELECT DISTINCT spend_date
FROM spending) AS t3
ON t.spend_date = t3.spend_date
AND t.platform = 'desktop'
GROUP BY t3.spend_date