子查询计算日期之间的天数

subquery calculate days between dates

子查询,SQL,Oracle

我是子查询的新手,希望得到一些帮助。我的想法是子查询将首先 运行 然后外部查询将基于 trans_code = 'ABC' 的子查询过滤器执行。该查询有效,但它从所有交易代码中提取所有日期,trans_code 'ABC' 和 'DEF' 等。

最终目标是计算日期之间的天数。

table结构是:

acct_num    effective_date
1234        01/01/2020
1234        02/01/2020
1234        03/01/2020
1234        04/01/2021

我想执行如下查询:

account     Effective_Date  Effective_Date_2   Days_Diff
1234        01/01/2020      02/01/2020         31  
1234        02/01/2020      03/01/2020         29
1234        03/01/2020      04/01/2021         395
1234        04/01/2021                         0

查询:

SELECT t3.acct_num,
       t3.trans_code,
       t3.effective_date,
       MIN (t2.effective_date) AS effective_date2,
       MIN (t2.effective_date) - t3.effective_date AS days_diff
FROM (SELECT t1.acct_num, t1.trans_code, t1.effective_date
      FROM lawd.trans t1
      WHERE t1.trans_code = 'ABC') t3
     LEFT JOIN lawd.trans t2 ON t3.acct_num = t2.acct_num
WHERE t3.acct_num = '1234' AND t2.effective_date > t3.effective_date
GROUP BY t3.acct_num, t3.effective_date, t3.trans_code
ORDER BY t3.effective_date asc

TIA!

使用lead():

select t.*,
       lead(effective_date) over (partition by acct_num order by effect_date) as next_efffective_date,
       (lead(effective_date) - effective_date) as diff
from lawd.trans t