支出表: Spending
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| user_id | int |
| spend_date | date |
| platform | enum |
| amount | int |
+-------------+---------+
這張表記錄了用戶在一個在線購物網站的支出歷史,該在線購物平臺同時擁有桌面端('desktop')和手機端('mobile')的應用程序。
這張表的主鍵是 (user_id, spend_date, platform)。
平臺列 platform 是一種 ENUM ,類型爲('desktop', 'mo每天 僅 使用手機端用戶、僅 使用桌面端用戶和 同時 使用桌面端和手機端的用戶人數和總支出金額bile')。
寫一段 SQL 來查找。
查詢結果格式如下例所示:
Spending table:
+---------+------------+----------+--------+
| user_id | spend_date | platform | amount |
+---------+------------+----------+--------+
| 1 | 2019-07-01 | mobile | 100 |
| 1 | 2019-07-01 | desktop | 100 |
| 2 | 2019-07-01 | mobile | 100 |
| 2 | 2019-07-02 | mobile | 100 |
| 3 | 2019-07-01 | desktop | 100 |
| 3 | 2019-07-02 | desktop | 100 |
+---------+------------+----------+--------+
Result table:
+------------+----------+--------------+-------------+
| spend_date | platform | total_amount | total_users |
+------------+----------+--------------+-------------+
| 2019-07-01 | desktop | 100 | 1 |
| 2019-07-01 | mobile | 100 | 1 |
| 2019-07-01 | both | 200 | 1 |
| 2019-07-02 | desktop | 100 | 1 |
| 2019-07-02 | mobile | 100 | 1 |
| 2019-07-02 | both | 0 | 0 |
+------------+----------+--------------+-------------+
在 2019-07-01, 用戶1 同時 使用桌面端和手機端購買, 用戶2 僅 使用了手機端購買,而用戶3 僅 使用了桌面端購買。
在 2019-07-02, 用戶2 僅 使用了手機端購買, 用戶3 僅 使用了桌面端購買,且沒有用戶 同時 使用桌面端和手機端購買。
select temp1.spend_date, temp1.platform,
ifnull(temp3.total_amount, 0) total_amount,
ifnull(temp3.total_users,0) total_users
from
(select distinct(spend_date), p.platform
from Spending,
(select 'desktop' as platform union
select 'mobile' as platform union
select 'both' as platform
) as p
) as temp1
left join
(select spend_date,platform, sum(amount) as total_amount, count(user_id) total_users
from
(select spend_date, user_id,
(case count(distinct platform)
when 1 then platform
when 2 then 'both'
end
) as platform, sum(amount) as amount
from Spending
group by spend_date, user_id
) as temp2
group by spend_date, platform
) as temp3
on temp1.platform = temp3.platform and temp1.spend_date = temp3.spend_date