簡體   English   中英

獲取SQL中同一列中兩個日期之間的天數

[英]Get number of days between 2 dates in the same column in SQL

目標:確定 2 個交易之間的生效日期差異大於 365 天的記錄。

表格示例:

account#    Effective_Date
1234        01/01/2020
1234        02/01/2020
1234        03/01/2020
1234        04/01/2021

我想創建一個看起來像這樣的表

account     Effective_Date  Effective_Date_1   Calculate_Days
1234        01/01/2020                         0  
1234        02/01/2020      01/01/2020         31
1234        03/01/2020      02/01/2020         29
1234        04/01/2021      03/01/2020         395

目標 1:在另一列“effective_date_1”中復制生效日期目標 2:將“effective_date_1”偏移 1 行

這在 SQL 中可能嗎?

使用lag() 在 SQL Server 中,這看起來像:

select t.*,
       datediff(day, lag(effective_date), effective_date) as num_days
from t;

注意:這會為第一行返回NULL 如果你真的想要0 ,那么 3 參數形式很方便:

select t.*,
       datediff(day, lag(effective_date, 1, effective_date), effective_date) as num_days
from t;

滯后語句必須與 over() 和 order by 一起使用。

select t.*
    ,lag(Effective_Date) over(order by Effective_Date)
    ,datediff(day, lag(Effective_Date) over(order by Effective_Date) , Effective_Date)
from (
    select  1234  as account#      ,'01/01/2020' as Effective_Date
    union
    select  1234  as account#      ,'02/01/2020' as Effective_Date
    union
    select  1234  as account#      ,'03/01/2020' as Effective_Date
    union
    select  1234  as account#      ,'04/01/2021' as Effective_Date
) t

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM