SQL实战 6.对于employees表中,给出奇数行的first_name

描述

对于employees表中,输出first_name排名(按first_name升序排序)为奇数的first_name
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');
输出格式:
first_name
Georgi
Anneke
因为Georgi按first_name排名为3,Anneke按first_name排名为1,所以会输出这2个,且输出时不需排序,即按原表顺序输出。
 

 

解题思路

 
解法1:用row_number函数进行排序,最后输出rn%2<>0的结果即可,但是这里题目要求是按照原表的顺序输出,而row_number()会改变顺序,这时可以join一下自己重新排序;
 
解法2:用count(*)函数取每个first_name对应有多少个小于自己的,那么假如有2个小于自己的,则当前first_name的排序为3,那么为技术,所以最后取count(*)为偶数的即可;

 

SQL如下

解法1:
SELECT b.first_name FROM 
employees b join 

(
SELECT first_name, ROW_NUMBER() OVER(ORDER BY first_name) N FROM employees
) a on b.first_name=a.first_name  WHERE a.n%2<>0 

 解法2:

SELECT first_name FROM
(
SELECT first_name , (SELECT COUNT(1) FROM employees  e2 WHERE e1.first_name>e2.first_name) rn FROM employees  e1
) e3 WHERE e3.rn%2=0

 

posted @ 2021-06-09 21:35  Transkai  阅读(158)  评论(0编辑  收藏  举报