sql - 如何根据日期查找每个 id 的最后一个复合键
问题描述
我正在使用 Oracle 开发人员,
并希望为我的表“bookborrow”找到每个 id 的最后一条记录,它有composite key
,id
并且dateofborrow
是主键(复合键)
列 :
id | studname | dateofborrow | bookname
----+------------+----------------+------------------------
1 | *Scotty* | 10-OCT-05 | DB Admin
1 | *Scotty* | 16-NOV-05 | Database Security
1 | *Scotty* | 09-DEC-06 | sql server 2005
2 | *Andy* | 30-MAR-04 | Math
2 | *Andy* | 14-JUN-06 | Calculation of matrix
3 | *Jack* | 29-JAN-09 | physics
如何根据这样的dateofborrow
输出找到每个 id 的最后一条记录?
id | studname | dateofborrow | bookname
----+------------+----------------+------------------------
1 | Scotty | 09-DEC-06 | sql server 2005
2 | Andy | 14-JUN-06 | Calculation of matrix
3 | Jack | 29-JAN-09 | physics
有什么帮助吗?
解决方案
你需要什么可以通过太多方式实现,这里有两个
with my_data_set as (
select 1 as id,'Scotty' as studname , '10-OCT-05' as dateofborrow,'DB Admin' as bookname from dual union
select 1 as id,'Scotty' as studname , '16-NOV-05' as dateofborrow,'Database Security' as bookname from dual union
select 1 as id,'Scotty' as studname , '09-DEC-06' as dateofborrow,'sql server 2005' as bookname from dual union
select 2 as id,'Andy' as studname , '30-MAR-04' as dateofborrow,'Math' as bookname from dual union
select 2 as id,'Andy' as studname , '14-JUN-06' as dateofborrow,'Calculation of matrix' as bookname from dual union
select 3 as id,'Jack' as studname , '29-JAN-09' as dateofborrow,'physics' as bookname from dual
)
select * from my_data_set a
where a.dateofborrow = (select max(to_date(dateofborrow,'DD-MONTH-YY')) from my_data_set where a.id = id);
with my_data_set as (
select 1 as id,'Scotty' as studname , '10-OCT-05' as dateofborrow,'DB Admin' as bookname from dual union
select 1 as id,'Scotty' as studname , '16-NOV-05' as dateofborrow,'Database Security' as bookname from dual union
select 1 as id,'Scotty' as studname , '09-DEC-06' as dateofborrow,'sql server 2005' as bookname from dual union
select 2 as id,'Andy' as studname , '30-MAR-04' as dateofborrow,'Math' as bookname from dual union
select 2 as id,'Andy' as studname , '14-JUN-06' as dateofborrow,'Calculation of matrix' as bookname from dual union
select 3 as id,'Jack' as studname , '29-JAN-09' as dateofborrow,'physics' as bookname from dual
)
select * from (
select a.*,row_number() over (partition by id order by to_date(dateofborrow,'DD-MONTH-YY') desc) r from my_data_set a
) where r =1;
推荐阅读
- python - 如何安装部分来自本地目录和部分来自公共存储库的依赖项?
- python - Is auth customization secure in django?
- kubernetes - How are Kuberenetes secrets stored on Amazon EKS
- javascript - 如何优化对象写入性能?
- ruby-on-rails - Postgres fails to connect to a solr Docker container
- r - 如何在数据框中添加一个布尔列,指示每个假期日期是否属于日期列
- oracle - ORA-20000: Oracle Text error: DRG-10599: column is not indexed where index exists on select "for update"
- c++ - 为什么我不能比较我的自定义类类型的两个向量?
- css - Bulma 表格行不跨越全宽
- python-3.x - How to assign specific color to rectangular region depend on an integer output in python and show that rectangular region on desktop?