计算2个日期之间的时差

时间:2014-11-15 07:04:00

标签: sql-server-2008

我正在计算票务系统中2个日期之间的时差。在主表中,我有RowID,TicketID,TicketCategory,CreatedMoment。故障单解析后,它将显示在Statuschange列中的另一个表上,两个表中的公共字段都是RowID。下面的示例表:

表1

RowID    TicketID    TicketCategory    Createdmoment      Status
1234     11223344    PC Installation   12 Nov 2014 0800    1
1235     11223355    Server Config     12 Nov 2014 0930    1

表2

TicketRowID    Statuschange      OldStatus   NewStatus
1234           13 Nov 2014 1300    1           2
1235           13 Nov 2014 1100    1           2

在上面的示例中,门票在第二天上午11点和下午1点得到解决,在我正在制作的报告中我计算在第二天中午12点之前解决的门票数量,因此在上面的示例报告中将显示我已关闭1机票和1待定。我必须运行查询上个月的数据以日常格式显示。需要有关正确代码的帮助。

1 个答案:

答案 0 :(得分:0)

希望以下代码段能够提供帮助:

declare @tab table (RowID int, TicketID varchar(100), TicketCategory varchar(100)
, Createdmoment datetime, [Status] int)

insert into @tab
select 1234,'11223344','PC Installation','12 Nov 2014 08:00',1
union
select 1235,'11223355','Server Config','12 Nov 2014 09:30',1


declare @tab2 table (TicketRowID int, Statuschange datetime, OldStatus int, NewStatus int)
insert into @tab2
select 1234, '13 Nov 2014 13:00',1, 2
union
select 1235, '13 Nov 2014 11:00', 1, 2

select *, dateadd(HH, 12, convert(datetime, cast(dateadd(day,1,t1.Createdmoment) as date))) NextDay12PM from @tab t1
select * from @tab2 t2

select t1.RowID, t1.TicketID, t1.TicketCategory, t1.Createdmoment, t2.Statuschange as 'Closedmoment', NewStatus
, case when t2.Statuschange <  dateadd(HH, 12, convert(datetime, cast(dateadd(day,1,t1.Createdmoment) as date))) then sum(1) else sum(0) end as 'Resolved'
, case when t2.Statuschange >  dateadd(HH, 12, convert(datetime, cast(dateadd(day,1,t1.Createdmoment) as date))) then sum(1) else sum(0) end as 'Pending'
from @tab t1
left join @tab2 t2 on t2.TicketRowID = t1.RowID
group by t1.RowID, t1.TicketID, t1.TicketCategory, t1.Createdmoment, NewStatus, t2.Statuschange 

感谢。