Oracle查询以获取同一表中相关行的先前值

标签 oracle

我有一个表 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/

相关文章:

oracle - 在FlywayDb迁移中使用 "connect sys as sysdba"时出错

sql - 简单的 Oracle SQL 日期语法问题

java - Oracle中基于rowid的更新

sql - Oracle 中的 Update-Set-From 语法问题

sql - 尝试替换列时出现 Oracle SQL 错误 "ORA-00984: column not allowed here"

oracle - "TIMESTAMP WITH TIME ZONE"<--> DateTImeOffset 映射不会在 INSERT 命令上传递区域部分( Entity Framework + Oracle)

database - 在 Oracle 中跟踪失败的用户连接

sql - 如何移动数据

sql - oracle插入很慢

java - 在 ibatis 中传递和返回自定义数组对象,在 java 中传递和返回 oracle