两个日期的sql差异

时间:2018-05-17 13:19:07

标签: sql sql-server date join

在sql server中,我有两个表:

Tran_Ex

Transactions

他们都有customer_id,这是加入表格的关键。

我想找到来自Date_Reported(来自Tran_ex)的Date_Received(来自交易)的工作日的差异。我想要一个包含这些数字的额外专栏:

例如

Date Reported | Date Received | Difference in days

提前致谢

2 个答案:

答案 0 :(得分:2)

使用DATEDIFF()函数()

您可以在此查询中获得工作日(周一至周五)的差异,因为银行假期您需要单独的逻辑。

Select Date_Reported, 
Date_Received ,
(DATEDIFF(dd, Date_Reported, Date_Received) + 1)
-(DATEDIFF(wk, Date_Reported, Date_Received) * 2)
-(CASE WHEN DATENAME(dw, Date_Reported) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, Date_Received) = 'Saturday' THEN 1 ELSE 0 END)
 AS Working_days_Difference
from Tran_Ex as tx
inner join
Transactions as tr
on(tx.customer_id = tr.customer_id)

修改了基于@scsimon的建议查询,不使用短号。

SELECT Date_Reported, 
   Date_Received , 
   datediff(day,((CASE WHEN Datename(weekday, Date_Reported) = 'Sunday' THEN 1 ELSE 0  END ) - (CASE WHEN Datename(weekday, Date_Received ) = 'Saturday' THEN 1 ELSE 0 END )),Datediff(day,(Datediff(week, Date_Reported, Date_Received ) * 2 ), 
   (Datediff(day, Date_Reported, Date_Received ) + 1 )))
   AS Working_days_Difference

    from Tran_Ex as tx
    inner join
    Transactions as tr
    on(tx.customer_id = tr.customer_id)

答案 1 :(得分:0)

使用DATEDIFF()功能:

select t.Date_Reported, t1.Date_Received,
       datediff(day, t.Date_Reported, t1.Date_Received) [Difference in days]
from Tran_Ex tx
inner join Transactions t on t.customer_id  = tx.customer_id;