想要添加从现有列计算的新列

时间:2016-11-19 06:08:42

标签: sql sql-server tsql sql-server-2012

我有一个插入了呼叫数据的表。现在我想计算接听时间和闭幕时间

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

3 个答案:

答案 0 :(得分:3)

这样的事情?

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

它获得了相同校准的下一个pictime。

答案 1 :(得分: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

答案 2 :(得分: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排名功能相同的工作(但我优先使用subqry,因为先前版本上不存在LEAD(例如MSSQL 2008 R2)。

如果您想添加列,最好将其添加到视图中。