两个时间段的天数计算问题

focusonline 2006-07-03 03:32:25
写一个这样的存储过程:
参数--sDate(开始日期),eDate(结束日期)
欲查询的表结构
ID Date1 Date2

用什么语句可以实现,传入sDate,eDate两个参数后,计算出和Date1,Date2日期段的交叉天数?
...全文
313 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
LiBin_OberthurCS 2006-07-03
  • 打赏
  • 举报
回复
declare @sDate datetime,@eDate datetime
set ...
select
case when (@sDate between Date1 and Date2) or (@eDate between Date1 and Date2)
then datediff(dd,
when @sDate<=Date1 then Date1 else @sDate end
when @sDate>=Date2 then Date2 else @eDate end)+1
when @sDate<Date1 and @eDate>Date1
then datediff(dd,Date1,Date2)+1
else 0
end
from
fcuandy 2006-07-03
  • 打赏
  • 举报
回复
将DECLARE @sdate DATETIME,@edate DATETIME
SET @sdate='2005-4-1'
SET @edate='2005-6-7'
改改,就是你要的存储过程了。
zjcxc 2006-07-03
  • 打赏
  • 举报
回复

CREATE PROC P_qry
@dt1 datetime,
@dt2 datetime
AS
DECLARE @dt datetime
IF @dt1 > @dt2
SELECT @dt = @dt1,
@dt1 = @dt2,
@dt2 = @dt

SELECT re = SUM(DATEDIFF(Day,
CASE WHEN Date1 < @dt1 THEN @dt1 ELSE Date1 END,
CASE WHEN Date2 < @dt2 THEN Date2 ELSE @dt2 END
) + 1)
FROM tb
WHERE Date1 <= @dt2
OR Date2 >= @dt1
GO

fcuandy 2006-07-03
  • 打赏
  • 举报
回复
DECLARE @tb TABLE(ID INT , Date1 DATETIME , Date2 DATETIME)
INSERT @tb SELECT 1,'2005-1-1','2005-6-9'
UNION ALL SELECT 2,'2005-7-2','2005-7-9'
UNION ALL SELECT 2,'2005-3-2','2005-5-9'

DECLARE @sdate DATETIME,@edate DATETIME
SET @sdate='2005-4-1'
SET @edate='2005-6-7'

SELECT Date1,Date2,sd,ed,
ISNULL(DATEDIFF(dd,
CASE WHEN sd>Date1 THEN sd ELSE Date1 END,
CASE WHEN ed>Date2 THEN Date2 ELSE ed END),0)
FROM @tb a
LEFT JOIN (SELECT @sdate sd,@edate ed) b
ON a.date2>=b.sd AND a.date1<=b.ed
focusonline 2006-07-03
  • 打赏
  • 举报
回复
再比如:
传入的两个参数为:
2006-7-1,2006-7-5
表中只有一条记录,Date1和Date2值分别为
2006-7-5,2006-7-9
那么结果应该为:
1
因为只有2006-7-5这天交叉了
LiBin_OberthurCS 2006-07-03
  • 打赏
  • 举报
回复
declare @sDate datetime,@eDate datetime

select datediff(dd,
case when @sDate<=Date1 then Date1
when @sDate>=Date2 then Date2
else @sDate
end,
case when @eDate<=Date1 then Date1
when @eDate>=Date2 then Date2
else @eDate
end)
from 表
focusonline 2006-07-03
  • 打赏
  • 举报
回复
比如:
传入的两个参数为:
2006-7-1,2006-7-5
表中只有一条记录,Date1和Date2值分别为
2006-7-3,2006-7-4
那么结果应该为:
2
因为只有2006-7-3,2006-7-4这两天交叉了
LouisXIV 2006-07-03
  • 打赏
  • 举报
回复
--难道是这样的?lz不要让人猜谜

select *
from tablename
where Date1>=@sDate and Date2<=eDate
playwarcraft 2006-07-03
  • 打赏
  • 举报
回复
交叉天數是什麼意思?我以為只是算兩者之間相差的天數...
playwarcraft 2006-07-03
  • 打赏
  • 举报
回复
select datediff(dd,date1,date2)
LouisXIV 2006-07-03
  • 打赏
  • 举报
回复
交叉天数??

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧