leetcode---sql题-----casewhen合集

1435制作会话柱状图

在这里插入图片描述
题解:首先我们需要使用case when将不同的时间区分开来

select session_id,case 
when duration >= 900 then '15 or more'
when duration >= 600 then '[10-15>'
when duration >= 300 then '[5-10>'
when duration >= 0   then '[0-5>'
end total
from Sessions

然后由于存在有些区间是没有人数的,那么我们需要使用union生成完整的区间格式

select '[0-5>' bin union
select '[5-10>' bin union
select '[10-15>' bin union
select '15 or more'  bin

接着我们需要对不同的区间使用group by进行计数

select total,count(*) nums from (
select session_id,case 
when duration >= 900 then '15 or more'
when duration >= 600 then '[10-15>'
when duration >= 300 then '[5-10>'
when duration >= 0   then '[0-5>'
end total
from Sessions
) F1 group by total

最终的结果需要使用union生成的列进行左连接

select bin,ifnull(nums,0) total from 
(select '[0-5>' bin union
select '[5-10>' bin union
select '[10-15>' bin union
select '15 or more'  bin) F2 left join 
(select total,count(*) nums from (
select session_id,case 
when duration >= 900 then '15 or more'
when duration >= 600 then '[10-15>'
when duration >= 300 then '[5-10>'
when duration >= 0   then '[0-5>'
end total
from Sessions
) F1 group by total) F3 on F2.bin = F3.total

提交结果如下
在这里插入图片描述

627 更改姓名

在这里插入图片描述
题目要求比较严格,只能使用update语句,不可以使用select语句,使用update语句可以为

update salary set sex=case when sex='m' then 'f' when sex='f' then 'm' end 

提交结果为
在这里插入图片描述
这里再给出一种使用select的方法,其实就是case when的使用。

select id,name,salary,case when sex='M' then 'F' when sex='F' then 'M' end sex from salary;

1468 计算税后工资

在这里插入图片描述
在这里插入图片描述
对于这个题目我们可以先查出每个公司的对应的税率应该是多少,我们可以增加一列辅助列进行判断,辅助列存的是对应的公司的工资的最大值。

select company_id,max(salary) max_salary from Salaries group by company_id

然后我们将Salaries表进行左连接后,可以使用case when对数据直接进行计算

select company_id,employee_id,employee_name,case when max_salary < 1000 then salary when max_salary < 10000 then round(salary*0.76,0) when max_salary >= 10000 then round(salary*0.51,0) end salary
from (
select S.*,max_salary from Salaries S left join (
select company_id,max(salary) max_salary from Salaries group by company_id) F1 on S.company_id = F1.company_id
) F2;

提交结果如下
在这里插入图片描述

608 树节点

在这里插入图片描述
我们根据树节点的三种类型进行判断就可以。
当父节点是null的时候,这个节点就是父节点。当节点没有孩子节点的时候就是叶子节点。其他情况就是中间节点。直接使用case when进行判断就可以

select id,case when p_id is null then 'Root' when id in (select distinct p_id from tree) then 'Inner' else 'Leaf' end Type from tree;

提交结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值