时间表内的日期

时间:2015-03-30 13:02:32

标签: sql-server datediff

我需要计算某些类型的活动之间的datedif(ss,start_time,end_time),我非常知道如何去做。我的代码是:

WITH WorkDates AS (
SELECT 
    ROW_NUMBER() OVER (PARTITION BY A.NUMBER ORDER BY datestamp DESC) AS RowNumber,
    p2.affected_item as Service,
    p1.close_time as close_time,
    datestamp,
    description,
    a.type,
    a.number as number
from ACTIVITYM1 a
left outer join probsummarym1 p1 on a.number = p1.number
inner join probsummarym2 p2 on p1.number = p2.number
where ((a.type like 'status%'
and (description like '%to Work In Progress%'
or description like '%from Work In Progress%'))  or a.type like 'Closed')
)
SELECT
O1.Service,
O1.number,
O1.close_time,
    sum(DATEDIFF(ss, O2.datestamp, O1.datestamp)) AS sum_of_time
FROM WorkDates O1
LEFT JOIN WorkDates O2
    ON O2.RowNumber = O1.RowNumber + 1
    and O2.number = O1.number
where O2.description like '%to Work In Progress%' 
and (O1.description like '%from Work In Progress%' or O1.type like 'Closed')
group by O1.Service, O1.number, O1.close_time
order by O1.Service, O1.number

我这样做,因为我需要在某些类型的活动之间进行计算,并且应该计算的许多这样的“时间窗口”不是恒定的。它工作得很好,但它计算全职,包括假期,周末

但我还需要做一件事。

我想计算datediff(ss,start_date,end_date),但仅限于星期一到星期五。这意味着,例如,如果start_date在星期五的16:00和end_date在星期一的7:00,则datediff应该是(24:00 - 16:00)+(07:00 - 00:00)= 15小时。有可能吗?

1 个答案:

答案 0 :(得分:2)

您应该计算周差,然后将其转换为秒,然后从datediff中扣除。 像这样:

sum(DATEDIFF(ss, O2.datestamp, O1.datestamp) - abs(DATEPART(ww,O2.datestamp) - DATEPART(ww,O1.datestamp)) * 2 * 24 * 60 * 60 ) AS sum_of_time