描述
对于employees表中,输出first_name排名(按first_name升序排序)为奇数的first_name
输出格式:
first |
---|
Georgi |
Anneke |
请你在不打乱原序列顺序的情况下,输出:按first_name排升序后,取奇数行的first_name。
如对以上示例数据的first_name排序后的序列为:Anneke、Bezalel、Georgi、Kyoichi。
则原序列中的Georgi排名为3,Anneke排名为1,所以按原序列顺序输出Georgi、Anneke。
示例1:
drop table if exists `employees` ;
CREATE TABLE `employees` (
`emp_no` int(11) NOT NULL,
`birth_date` date NOT NULL,
`first_name` varchar(14) NOT NULL,
`last_name` varchar(16) NOT NULL,
`gender` char(1) NOT NULL,
`hire_date` date NOT NULL,
PRIMARY KEY (`emp_no`));
INSERT INTO employees VALUES(10001,'1953-09-02','Georgi','Facello','M','1986-06-26');
INSERT INTO employees VALUES(10002,'1964-06-02','Bezalel','Simmel','F','1985-11-21');
INSERT INTO employees VALUES(10005,'1955-01-21','Kyoichi','Maliniak','M','1989-09-12');
INSERT INTO employees VALUES(10006,'1953-04-20','Anneke','Preusig','F','1989-06-02');
输出:
Georgi
Anneke
我的解题思路:
题目的难点是如何按照原来的顺序输出,我将原来的顺序记录一下,再排序就很好解决了
- 利用窗口函数row_number进行排序,排序需要对原顺序和新顺序都记录一下
- 根据新顺序筛选出排名奇数的,根据原顺序输出答案
select first_name
from (
select first_name,
row_number() over () as old_num,
row_number() over (order by first_name) as new_num
from employees
) t
where new_num % 2 = 1
order by old_num
;
标签:name,employees,SQL255,Anneke,Georgi,NULL,first
From: https://www.cnblogs.com/moliyy/p/17672295.html