使用SQL Server 2008我想计算在给定日期范围内16:30到18:00之间的分钟数。
因此输入例如@fromdate = ' 2017-04-17 17:00:00' 和@todate = ' 2017-04- 19 17:00:00'
所以对于上面使用拉门数学的例子。
Day 1 (17th) : 60
Day 2 (18th) : 90
Day 3 (19th) : 30
Total 180
第1天是60,因为从开始日期17:00到18:00之间有60分钟。第2天是90,因为中间日期必须是16:30到18:00之间的完整90分钟,第3天是30在16:30到17:00之间有30分钟(结束日期的时间)所以如果有意义的话,我每天都会在16:30到18:00之间搜索分钟数。
我希望总数是输出。
答案 0 :(得分:2)
这将在sql server中运行。我们在cte中填充开始和结束日期时间。在那之后,它就像在几分钟内总结日期差异一样简单:
declare @fromdate datetime = convert(datetime,'2017-04-17 17:00:00',20)
declare @todate datetime = convert(datetime,'2017-04-19 17:00:00',20)
declare @startRangeTime time = '16:30';
declare @endRangeTime time = '18:00';
with dates as (
select top (datediff(day, @fromdate, @toDate) + 1)
case when dateadd(day,row_number() over (order by a.object_id) - 1, cast(@fromdate as date)) = cast(@fromdate as date)
then @fromdate
else cast(dateadd(day,row_number() over (order by a.object_id) - 1, cast(@fromdate as date)) as datetime) + cast(@startRangeTime as datetime)
end as startDt,
case when dateadd(day,row_number() over (order by a.object_id) - 1, cast(@fromdate as date)) = cast(@todate as date)
then @todate
else cast(dateadd(day,row_number() over (order by a.object_id) - 1, cast(@fromdate as date)) as datetime) + cast(@endRangeTime as datetime)
end as endDt
from sys.all_objects a
cross join sys.all_objects b
)
select sum(datediff(mi, startDt, endDt)) from dates
返回:
180
答案 1 :(得分:0)
你不能减去2个字符串,所以这样做。用于获取2个日期之间的分钟时间的示例代码。
ALTER SESSION SET NLS_LANGUAGE="American"
WITH source as (
SELECT '30-OCT-2016 21:08:34' as A, '30/10/2016 21:06:34' as B
FROM Dual
)
SELECT TO_DATE(A, 'DD-MON-YYYY HH24:MI:SS') as new_a,
TO_DATE(B, 'DD/MM/YYYY HH24:MI:SS') as new_b,
( TO_DATE(A, 'DD-MON-YYYY HH24:MI:SS')
- TO_DATE(B, 'DD/MM/YYYY HH24:MI:SS')
) * 24 * 60 as result
FROM source
希望这会有所帮助......