博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Oracle样例数据库(SCOTT)的SQL查询题
阅读量:3907 次
发布时间:2019-05-23

本文共 1043 字,大约阅读时间需要 3 分钟。

请用一条sql语句查询出scott.emp表中每个部门工资前三位的数据,显示结果如下:

DEPTNO    SAL1      SAL2       SAL3

---------------- ---------- ------------

    10         5000       2450       1300

    20         3000       2975       1100

   30          2850       1600       1500 则,该语句为:

SELECT	deptno,	max( sal ) sal1,	max(decode( RN, 2, sal )) sal2,	min( sal ) sal3 FROM	(SELECT	* FROM	( SELECT DEPTNO, SAL, ROW_NUMBER () OVER ( PARTITION BY DEPTNO ORDER BY SAL DESC ) AS RN FROM EMP ) WHERE	RN <= 3 	) GROUP BY	deptno

下面来分析一下这个题

1.首先将emp表按deptno进行分组,取出分组后的前3条数据

SELECT	* FROM	( SELECT DEPTNO, SAL, ROW_NUMBER () OVER ( PARTITION BY DEPTNO ORDER BY SAL DESC ) AS RN FROM EMP ) WHERE	RN <= 3

row_number() over()函数,用于给数据库表中的记录进行标号,在使用的时候,其后还跟着一个函数 over(),而函数 over() 的作用是将表中的记录进行分组和排序

即:ROW_NUMBER() OVER(PARTITION BY 分组的字段名 ORDER BY 排序的字段名)

2.将上面的查询作为子查询

SELECT	deptno,	max( sal ) sal1,	max(decode( RN, 2, sal )) sal2,	min( sal ) sal3 FROM	(SELECT	* FROM	( SELECT DEPTNO, SAL, ROW_NUMBER () OVER ( PARTITION BY DEPTNO ORDER BY SAL DESC ) AS RN FROM EMP ) WHERE	RN <= 3 	) GROUP BY	deptno

使用decode()函数判断字符串是否一样,DECODE(value,if1,then1,if2,then2,if3,then3,...,else)

转载地址:http://csqen.baihongyu.com/

你可能感兴趣的文章
Tech Blog
查看>>
Logon System Design
查看>>
Python yield
查看>>
Sina API OAuth
查看>>
Python supervisor
查看>>
dict & set
查看>>
Common Multiple and Least Common Multiple(LCM)
查看>>
Greatest Common Divisor (GCD) - Euclidean algorithm
查看>>
Regular Expression Python
查看>>
大数据处理
查看>>
Mapreduce 通俗版
查看>>
MapReduce Inverted index
查看>>
MapReduce Intro
查看>>
Mapreduce Patterns, Algorithms, and use cases
查看>>
Hadoop interview
查看>>
数据处理问题
查看>>
BloomFilter
查看>>
Bloom Filter - Math deduce
查看>>
Bit Byte Megabyte Gigabyte
查看>>
Bits Bytes and Words
查看>>