【SQL日常刷题 LeetCode Hard】1127. 用户购买平台1127. User Purchase Platform
解题思路
临时别名表v1查询每个用户,每天在多少个平台下单,统计用户每日使用平台数platform_count
按题目要求,如果某人没有同时在两个平台下单的用户,也需要显示该字段为0,
所以临时别名表v2,v3为日期+平台全连接,便于后续连接使用
子查询判断一个用户当天是否在两个平台下单platform_count,等于2则显示为both,否则就只显示平台名称。
selectSpending.user_id,Spending.spend_date,casewhen v1.platform_count = 2 then 'both'when v1.platform_count = 1 then Spending.platformelse 'chk'end platform,Spending.amount,v1.platform_countfromSpendingleft join v1 on Spending.user_id = v1.user_idand Spending.spend_date = v1.spend_date
t2中的第一个group by 仅聚合了金额(将多条条both记录合并为一条,金额相加)得到t2_1,第二个group by计算金额和用户数的聚合得到t2_2
(selectspend_date,platform,sum(amount) as total_amount,count(user_id) as total_usersfrom(selectspend_date,platform,user_id,sum(amount) as amountfrom(selectSpending.user_id,Spending.spend_date,casewhen v1.platform_count = 2 then 'both'when v1.platform_count = 1 then Spending.platformelse 'chk'end platform,Spending.amount,v1.platform_countfromSpendingleft join v1 on Spending.user_id = v1.user_idand Spending.spend_date = v1.spend_date) as t2_1group byspend_date,platform,user_id) as t2_2group byspend_date,platform) as t2
完整代码
# # Write your MySQL query statement belowwith v1 as (selectuser_id,spend_date,count(platform) as platform_countfrom(selectuser_id,spend_date,platform,sum(amount) as amountfromSpendinggroup byuser_id,spend_date,platform) as t1group byuser_id,spend_date),v2 as(selectplatformfromSpendinggroup byplatformunionselect'both' as platform),v3 as(selectspend_datefromSpendinggroup byspend_date)selectt1.spend_date,t1.platform,coalesce(t2.total_amount, 0) as total_amount,coalesce(t2.total_users, 0) as total_usersfrom(selectspend_date,platformfromv2,v3) as t1left join (selectspend_date,platform,sum(amount) as total_amount,count(user_id) as total_usersfrom(selectspend_date,platform,user_id,sum(amount) as amountfrom(selectSpending.user_id,Spending.spend_date,casewhen v1.platform_count = 2 then 'both'when v1.platform_count = 1 then Spending.platformelse 'chk'end platform,Spending.amount,v1.platform_countfromSpendingleft join v1 on Spending.user_id = v1.user_idand Spending.spend_date = v1.spend_date) as t2_1group byspend_date,platform,user_id) as t2_2group byspend_date,platform) as t2 on t1.spend_date = t2.spend_dateand t1.platform = t2.platform
