简体   繁体   English

如何比较不同记录的两个不同列的日期?

[英]How to compare dates of two different columns for different records?

I have a table that contains two different status per user, "claimed" and "returned".我有一个表,其中包含每个用户的两种不同状态,“已声明”和“已返回”。 I want to compare the 'status_datetime_update' date of the 'returned' status and check if it is greater or less than the expiration_datetime of the previous status ('claimed').我想比较“返回”状态的“status_datetime_update”日期,并检查它是大于还是小于前一个状态(“已声明”)的 expire_datetime。

I know transaction_id 1111 and 1244 are less than and transaction_id 3312 is greater than.我知道 transaction_id 1111 和 1244 小于而 transaction_id 3312 大于。

Is there a way I can do this?有没有办法做到这一点?

在此处输入图片说明

create or replace table TBL_A (
    user_name varchar, country varchar, status varchar, transaction_id varchar, status_datetime_update date, expiration_datetime date
);
insert into TBL_A values 
('Rachel', 'USA', 'CLAIMED','1111', '2021-10-10', '2021-10-15'),
('Rachel', 'USA', 'RETURNED','1111', '2021-10-14','2021-10-15'),
('Ross', 'PAN', 'CLAIMED','3312','2021-10-12','2021-10-20'),
('Ross', 'PAN', 'RETURNED','3312', '2021-10-25','2021-10-20'),
('Chandler', 'UK', 'CLAIMED','1244','2021-09-11','2021-09-14'),
('Chandler', 'UK', 'RETURNED', '1244','2021-09-12','2021-09-14');

Something like this?像这样的东西?

select *, 
LAG( expiration_datetime ) OVER (PARTITION BY transaction_id ORDER BY status) <= status_datetime_update expired
from tbl_a;

By the way, your rows already contain the same expiration_datetime value.顺便说一下,您的行已经包含相同的 expire_datetime 值。 Why not to use it?为什么不使用它?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM