专业编程基础技术教程

网站首页 > 基础教程 正文

「SQL」力扣-550、577、586

ccvgpt 2024-08-04 12:24:39 基础教程 18 ℃

【力扣-550】

表:

「SQL」力扣-550、577、586

问题:计算从首次登录日期开始至少连续两天登录的玩家的数量,然后除以玩家总数。

思路解析:

先通过分组(group by)求出每个用户的最早(min)登录日期,将该表作为a表,然后和activity再次进行关联,关联条件为a、b表的player_id相等且b表的日期与a表的日期相差一天,最后统计b表的用户数量、a表的用户数量,求差值即可。

解答:

select 
	round(count(distinct b.player_id)/count(distinct a.player_id),2) fraction
from 
(
select
    player_id,
min(event_date) as first_login
from Activity
group by player_id
) a 
left join activity b 
on a.player_id=b.player_id and datediff(b.event_date, a.first_login)=1


【力扣-577】

表:

问题:查询bonus<1000的员工的name以及其bonus。

思路解析:

因为要查询所有员工的信息,所以先进行左关联(left join),以employee为左表、bonus为右表;

然后对关联后的表进行筛选(where),用户的bonus<1000有两种情况:a、用户有bonus但是<1000,b、用户没有bonus,也就是null。

解答:

select
  a.name,
  b.bonus 
from Employee a 
left join Bonus b 
on a.EmpId=b.EmpId 
where b.bonus is null 
or b.bonus<1000 


【力扣-586】

表:

问题:查询订单最多的客户。

思路解析:

orders表为每个用户的下单明细情况,所以对customer_number分组(group by),统计(count)每个用户的订单数量,然后按照订单数量降序排序(order by ... desc),最后取出第一条数据即可(limit)。

解答:

select 
  customer_number 
from orders 
group by customer_number 
order by count(order_number) desc 
limit 1 

好了,今天的分享就到这里,喜欢的话点个赞吧~

更多sql、excel、面试题、面经移步公众号:数据怎么玩

Tags:

最近发表
标签列表