Skip to content

1127. User Purchase Platform

 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
WITH
  UserToAmount AS (
    SELECT
      user_id,
      spend_date,
      CASE
        WHEN COUNT(DISTINCT platform) = 2 THEN 'both'
        ELSE platform
      END AS platform,
      SUM(amount) AS amount
    FROM Spending
    GROUP BY 1, 2
  ),
  DateAndPlatforms AS (
    SELECT DISTINCT(spend_date), 'desktop' AS platform
    FROM Spending
    UNION ALL
    SELECT DISTINCT(spend_date), 'mobile' AS platform
    FROM Spending
    UNION ALL
    SELECT DISTINCT(spend_date), 'both' AS platform
    FROM Spending
  )
SELECT
  DateAndPlatforms.spend_date,
  DateAndPlatforms.platform,
  IFNULL(SUM(UserToAmount.amount), 0) AS total_amount,
  COUNT(DISTINCT UserToAmount.user_id) AS total_users
FROM DateAndPlatforms
LEFT JOIN UserToAmount
  USING (spend_date, platform)
GROUP BY 1, 2;