我有一个表 Student,其中有名称和年度评分。
Name Year Rating
Ram 2016 10
Sam 2016 9
Ram 2014 8
Sam 2012 7
我需要找到该员工之前的评分,可能是去年或几年前。
查询应返回以下结果
Name Cur_rating_year_2016 Prev_rating
Ram 10 8
Sam 9 7
下面是插入和创建的脚本
Create table Student (name varchar2(10), year number, rating number );
insert into student values('Ram' ,2016 ,10);
insert into student values('Sam' ,2016 ,9);
insert into student values('Sam' ,2012 ,7);
insert into student values('Ram' ,2014 ,8);
有没有办法使用选择查询来实现这一点?
最佳答案
使用 LAG
解析函数https://docs.oracle.com/database/122/SQLRF/LAG.htm#SQLRF00652
LAG is an analytic function. It provides access to more than one row of a table at the same time without a self join. Given a series of rows returned from a query and a position of the cursor, LAG provides access to a row at a given physical offset prior to that position.
For the optional offset argument, specify an integer that is greater than zero. If you do not specify offset, then its default is 1. The optional default value is returned if the offset goes beyond the scope of the window. If you do not specify default, then its default is null.
SELECT stud_name AS name,
r_year AS year,
r_value AS rating,
lag(r_value, 1, NULL) OVER(PARTITION BY stud_name ORDER BY r_year) AS prev_rating
FROM stud_r
ORDER BY stud_name;
关于Oracle查询以获取同一表中相关行的先前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41256944/