看到的几个好玩SQL题
一般来说SQL题都是考验窗口函数,这里也进行一些用法的总结
书写一个SQL 查询,查找至少连续三次的数字
根据id进行排序,查找Num连续出现三次的数字
select distinct Num
from
(select Num, lead(Num,1,null) over(order by id) n2.
(select Num, lead(Num,2,null) over(order by id) n3,
From logs ) t1
Where Num = n2 and Num = n3
不同公司的员工薪资中位数
Select id,Company,Salary
From (
Select id,Company,Salary
ROW_NUMBER() over(partition by Company order by Salary) rk
Count(*) over(partition by Company) cnt
From Employee
) t1
Where rk in (Floor(cnt + 1) / 2)
如果一个用户,在注册之后的第二天还登录过了,那么就认为这个用户是个优质用户,这个题就是计算优质用户占比
Select round(avg(a.event_date is not null), 2) fraction
From
(select player_id, min(event_date) as login from activity group by player_id) p
Left join activity a
On p.player_id=a.player_od and diff(a.event_date,p.login) = 1
我们有一个如下表格
我们需要累加所有投资成功者在2016年的投资
如何定义投资成功者呢?
2015年的投资额度需要和至少一个其他投保人在2015投资额度相同
所在经纬度和其他投资人不同
Select sum(TIV_2016)
From (
Select TIV_2016,cnt,
Count(*) over(partition by loc) lcnt
From ( select TIV_2016,count(TIV_2015) over(partition by TIV_2015) cnt,
Concat_ws(LAT,LON) loc
From the_table) t1
)t2
Where lcnt = 1 and cnt != 1