如何解决在Redshift SQL中查找指定日期之前的最大日期
我在SQL(AWS Redshift)中有一个表(表A),在这里我隔离了包含帐户ID和日期的起始填充。我想从该表中获取输出,然后将LEFT联接回到“帐户”表,以仅从我的输出中返回存储在该表中的日期之前或之后的开始日期。
Table A (Beg Pop)
-------
select account_id,min(start_date),min(end_date)
from accounts
group by 1;
我只想返回当前表中account_id匹配的日期之前的日期。我正在寻找类似...
Table B
-------
select a.account_id,a.start_date,a.end_date,b.start_date_prev,b.end_date_prev
from accounts as a
left join accounts as b on a.account_id = b.account_id
where max(b.start_date) less than a.start_date;
最终,我想返回表a中的所有内容,并且只返回max(start_date)小于表A中的start_date的日期。我知道WHERE子句中不允许聚合,我想我可以执行子查询,但是我只想在输出中的日期之前输入最大日期。任何建议都将不胜感激。
解决方法
我只想返回当前表中account_id匹配的日期之前的日期
如果要给定行的上一个日期,请使用lag()
:
select a.*,lag(start_date) over (partition by account_id order by start_date) as prev_start_date
from accounts a;
,
据我所知,该要求是显示基表中的所有行,并根据列和某些条件对先行数据进行排序
请检查以下我从文章Select Next and Previous Rows with Current Row using SQL CTE Expression摘录的示例
WITH CTE as (
SELECT
ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY start_date) as RN,*
FROM accounts
)
SELECT
PreviousRow.*,CurrentRow.*,NextRow.*
FROM CTE as CurrentRow
LEFT JOIN CTE as PreviousRow ON
PreviousRow.RN = CurrentRow.RN - 1 and PreviousRow.account_id = CurrentRow.account_id
LEFT JOIN CTE as NextRow ON
NextRow.RN = CurrentRow.RN + 1 and NextRow.account_id = CurrentRow.account_id
ORDER BY CurrentRow.account_id,CurrentRow.start_date;
我使用以下示例数据进行了测试,它似乎可以正常工作
create table accounts(account_id int,start_date date,end_date date);
insert into accounts values (1,'20201001','20201003');
insert into accounts values (1,'20201002','20201005');
insert into accounts values (1,'20201007','20201008');
insert into accounts values (1,'20201011','20201013');
insert into accounts values (2,'20201002');
insert into accounts values (2,'20201015','20201016');
输出如下
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。