两个日期的sql差异

两个日期的sql差异,sql,sql-server,date,join,Sql,Sql Server,Date,Join,在sql server中,我有两个表: Tran_Ex Transactions 它们都有customer\u id,这是加入表的关键 我想找出报告的日期(来自交易)与收到的日期(来自交易)的工作日差异。我想增加一个列,列有这些数字: 乙二醇 提前感谢使用DATEDIFF()函数: select t.Date_Reported, t1.Date_Received, datediff(day, t.Date_Reported, t1.Date_Received) [Differe

在sql server中,我有两个表:

Tran_Ex

Transactions
它们都有
customer\u id
,这是加入表的关键

我想找出报告的
日期
(来自交易)与收到的
日期
(来自交易)的工作日差异。我想增加一个列,列有这些数字:

乙二醇

提前感谢

使用
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; 
使用函数()

您可以从该查询中获得工作日(周一至周五)差异,对于银行假期,您需要单独的逻辑

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)

寻找
DATEDIFF
函数。DATEDIFF解决方案看起来是一个很好的开始。但你说的是工作日。这通常意味着您希望排除周末和节假日。除了datediff之外,您还希望在此处使用日历表。您可以在此处阅读有关日历表的更多信息。非常感谢,这只考虑到工作日(不包括周末和银行假日),不考虑任何周末或假日。这只是天数。请看我对你原来问题的评论。在你原来的回答中,你没有使用速记,然后你更改了它。我鼓励你不要在datetime格式中使用速记。另外,你需要确定他们的设置是什么,这样才能起作用谢谢你的建议@scsimon,添加了没有速记的查询@TanveerSinghBhatia没有问题,但是你又错过了速记。如果不是
datediff(dd,
,它将是
datediff(day,
,同样对于
wk
dw
。看看那篇文章吧。再次感谢@scsimon,也换了datepart速记
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)