题解 |
给出employees表中排名为奇数行的first_name
https://www.nowcoder.com/practice/e3cf1171f6cc426bac85fd4ffa786594
题解:
刚开始想法是使用窗口函数,对first_name进行赋值,然后直接返回结果,但执行完结果报错。
select t.first_name
from (select first_name,rank() over(order by first_name) as d from employees) as twhere t.d %2 = 1 ---- 错误代码
后面也是翻了评论区,才看见要求保持原first_name的顺序,然后选出奇数的
所有吧答案修改为如下代码:
select e.first_name
from employees e join (select first_name,rank() over(order by first_name) as d from employees) as t
on e.first_name = t.first_name
where t.d %2 = 1
代码解释:用表连接的原因是,先通过窗口函数对first_name进行赋值,然后与原表关联,因为原表的first_name的顺序是原始顺序, 俩表关联后只要找出奇数行就可以了。