OVER(PARTITION BY)高级查询

--基础数据
DROP TABLE "ZYH_TEST";
CREATE TABLE "ZYH_TEST" (
  "ID" NUMBER(19) NOT NULL ,
  "NAME" VARCHAR2(255 BYTE) ,
  "CREATETIME" DATE ,
  "SCORE" NUMBER ,
  "CLASSID" VARCHAR2(255 BYTE) 
)

INSERT INTO "ZYH_TEST" VALUES ('1', 'allen', TO_DATE('2019-01-14 17:41:09', 'SYYYY-MM-DD HH24:MI:SS'), '98.5', '1');
INSERT INTO "ZYH_TEST" VALUES ('2', 'lee', TO_DATE('2019-01-14 17:41:37', 'SYYYY-MM-DD HH24:MI:SS'), '88.5', '1');
INSERT INTO "ZYH_TEST" VALUES ('3', 'me', TO_DATE('2019-01-14 17:41:52', 'SYYYY-MM-DD HH24:MI:SS'), '73', '1');
INSERT INTO "ZYH_TEST" VALUES ('4', 'let', TO_DATE('2019-01-14 17:42:03', 'SYYYY-MM-DD HH24:MI:SS'), '88', '1');
INSERT INTO "ZYH_TEST" VALUES ('5', 'met', TO_DATE('2019-01-14 17:42:16', 'SYYYY-MM-DD HH24:MI:SS'), '99', '1');
INSERT INTO "ZYH_TEST" VALUES ('6', 'ali', TO_DATE('2019-01-14 17:42:30', 'SYYYY-MM-DD HH24:MI:SS'), '66', '1');

1,lead()/lag()

SELECT
	t.name 姓名,
	t.score 当前分数,
	lead ( t.score, 1, 0 ) over ( partition BY t.classid ORDER BY t.score ) 后一行值,--lead(列名,n,m),当前记录后n行的数据,没有则取默认值m。不带n,m参数,取后一行
	lag ( t.score, 1, 0 ) over ( partition BY t.classid ORDER BY t.score ) 前一行值,--lag(列名,n,m),当前记录前n行的数据,没有则取默认值m。不带n,m参数,取前一行
	nvl( t.score - lead ( t.score ) over ( partition BY t.classid ORDER BY t.score ), 0 ) 与后一行差值,
	nvl( t.score - lag ( t.score ) over ( partition BY t.classid ORDER BY t.score ), 0 ) 与前一行差值 
FROM
	ZYH_TEST t;

OVER(PARTITION BY)高级查询_第1张图片

2,其他用法

SELECT
	t.name 姓名,
	t.score 当前分数,
	min ( t.score ) over ( partition BY t.classid ) 最小值,
	max ( t.score ) over ( partition BY t.classid ) 最大值,
	sum( t.score ) over ( partition BY t.classid ) 累计值,
	avg( t.score ) over ( partition BY t.classid ) 平均值,
	count( t.score ) over ( partition BY t.classid ) 统计个数,
	row_number () over ( partition BY t.classid ORDER BY t.score ) 排序号 
FROM
	ZYH_TEST t;

OVER(PARTITION BY)高级查询_第2张图片

SELECT
	t.name 姓名,
	t.score 当前分数,
	min( t.score ) over ( partition BY t.classid  ORDER BY t.score) 最小值,
	max( t.score ) over ( partition BY t.classid  ORDER BY t.score) 最大值,
	sum( t.score ) over ( partition BY t.classid  ORDER BY t.score) 累计值,
	avg( t.score ) over ( partition BY t.classid  ORDER BY t.score) 平均值,
	count( t.score ) over ( partition BY t.classid  ORDER BY t.score) 统计个数,
	row_number () over ( partition BY t.classid ORDER BY t.score ) 排序号 
FROM
	ZYH_TEST t;

OVER(PARTITION BY)高级查询_第3张图片

你可能感兴趣的:(Oracle)