2016-11-19 72 views
0

我有一個插入呼叫數據的表。現在我想要計算picktime和呼叫的關閉時間想要添加從現有列計算得出的新列

Create table calldata 
(
    calldate Datetime, 
    picktime datetime, 
    status varchar(50) 
) 

insert into calldata 
values('2016-11-18 04:43:37 PM','2016-11-18 04:43:57 PM','ATTENDED') 

insert into calldata 
values('2016-11-18 04:43:37 PM','2016-11-18 04:44:25 PM','ESCALATED') 

insert into calldata 
values('2016-11-18 04:43:37 PM','2016-11-18 04:49:52 PM','ESCALATED') 

insert into calldata 
values('2016-11-18 04:43:37 PM','2016-11-18 04:50:20 PM','CLOSED') 

select * from calldata 

輸出:

calldate    | picktime     | status 
-------------------------------------------------------------- 
2016-11-18 16:43:37.000 | 2016-11-18 16:43:57.000 | ATTENDED 
2016-11-18 16:43:37.000 | 2016-11-18 16:44:25.000 | ESCALATED 
2016-11-18 16:43:37.000 | 2016-11-18 16:49:52.000 | ESCALATED 
2016-11-18 16:43:37.000 | 2016-11-18 16:50:20.000 | CLOSED 

現在我想這樣的數據,從上面的表格:

calldate    | picktime     | CloseTime    | status 
------------------------------------------------------------------------------------------- 
2016-11-18 16:43:37.000 | 2016-11-18 16:43:57.000 | 2016-11-18 16:44:25.000 | ATTENDED 
2016-11-18 16:43:37.000 | 2016-11-18 16:44:25.000 | 2016-11-18 16:49:52.00 | ESCALATED 
2016-11-18 16:43:37.000 | 2016-11-18 16:49:52.000 | 2016-11-18 16:50:20.00 | CLOSED 
2016-11-18 16:43:37.000 | 2016-11-18 16:50:20.000 |       | CLOSED 
+0

你確定你想要的CLOSE_TIME作爲下一個呼叫的picktime? –

+0

不適用於下一次呼叫,希望close_time來自同一個特定移動電話的呼叫否 – mansi

+0

此數據僅適用於一個號碼。我想同樣爲不同的移動號碼 – mansi

回答

3

這樣的事情?

LEAD(picktime, 1, null) OVER (PARTITION BY calldate ORDER BY picktime)? 

它得到相同的calldate的下一個pictime。

0
Begin Tran 

Create table calldata (calldate Datetime,picktime datetime,status varchar(50)) 

insert into calldata values('2016-11-18 04:43:37 PM','2016-11-18 04:43:57 PM','ATTENDED') 
insert into calldata values('2016-11-18 04:43:37 PM','2016-11-18 04:44:25 PM','ESCALATED') 
insert into calldata values('2016-11-18 04:43:37 PM','2016-11-18 04:49:52 PM','ESCALATED') 
insert into calldata values('2016-11-18 04:43:37 PM','2016-11-18 04:50:20 PM','CLOSED') 


select calldate,picktime,LEAD(picktime,1) OVER (ORDER BY picktime)as CloseTime,status from calldata 
RollBack Tran 
0

隨着子查詢是活的輕鬆:

select *, 
    (
    select top 1 d.picktime from calldata d 
    where d.picktime > c.picktime 
    order by d.picktime asc) previous_picktime 
from calldata c 

這QRY做同樣的工作LEAD排名函數(但我prefere使用subqry由於鉛不上以前的版本存在(例如2008 MSSQL R2)。

如果你想添加列是要加入到這一觀點最好的方式。