在SQL Server 2008中计算以分钟为单位的时差

时间:2017-05-01 14:29:55

标签: sql sql-server sql-server-2008 tsql

我在SQL server 2008中有一个包含数据的表。 表包含组织根据请求处理的时间量的数据

CREATE TABLE support 
(    ID varchar(50), 
     IN_ORGANIZATION varchar(MAX),    
     FROM_ORGANIZATION varchar(MAX),
     TIMEDIF datetime                );

INSERT INTO support
(ID, IN_ORGANIZATION,FROM_ORGANIZATION,TIMEDIF )


VALUES
('22907','ORGANIZATION_NAME_1','RODLAY LLP','2017-04-15 14:58:00.000'),

('22907','MARY LOAN','ORGANIZATION_NAME_1','2017-04-15 15:00:00.000'),


('23289','VENIXTON Ltd','ORGANIZATION_NAME_1','2017-04-21 11:00:00.000'),

('23289','ORGANIZATION_NAME_1','Ocean Loan','2017-04-21 12:00:00.000'),

('23289','Ocean Loan','ORGANIZATION_NAME_1','2017-04-21 13:00:00.000')

;

我想找时间工作组织提出请求:ORGANIZATION_NAME_1。     帮我写CURSOR来计算时间。

Result:
ID, TIMEDIF(minutes)
22907, 2
23289, 120

3 个答案:

答案 0 :(得分:0)

也许此查询可以帮助您:

select 
   id, 
   DATEDIFF(m,MIN(TIMEDIF),MAX(TIMEDIF)) as [TIMEDIF(minutes)] 
from support
    where IN_ORGANIZATION ='ORGANIZATION_NAME_1' 
       or FROM_ORGANIZATION ='ORGANIZATION_NAME_1'
group by id

答案 1 :(得分:0)

如果您只是试图获取行之间的TimeDifferences,您可以尝试这样的事情:

; WITH x AS
(
    SELECT *, ROW_NUMBER() OVER(ORDER BY id) AS rwn
From dbo.support
)
SELECT 
  x.ID
, y.ID AS NextID
, x.IN_ORGANIZATION
, y.IN_ORGANIZATION NextInOrg
, x.FROM_ORGANIZATION
, y.FROM_ORGANIZATION NextFromOrg
, x.TIMEDIF
, y.TIMEDIF AS NextTimeDiff
, x.rwn
, DATEDIFF(MINUTE, x.TIMEDIF, y.TIMEDIF) AS DifferenceFromOneToTheNext
FROM x 
    INNER JOIN x y ON x.rwn = y.rwn - 1

如果你输入一个自我种子的身份,你已经可以得到一个指针供参考。这实际上是任意的。

答案 2 :(得分:0)

Datediff 功能可以解决问题

select id,datediff(minute,min(timedif),max(timedif) ) AS time from support 
where in_organization = 'ORGANIZATION_NAME_1' or from_organization = 'ORGANIZATION_NAME_1'  
group by id ;    

我的输出:

    |id     |time
1   |22907  |2
2   |23289  |120

如果有任何疑问,请告知。