用于检查每个故障单的状态的SQL查询作为持续时间

时间:2015-03-04 10:57:22

标签: sql-server

我有一张桌票,里面有ticketid,owner,ownerdate列。我想计算处理它的每张票的持续时间。表是......

ticketid  owner     owndate
1001     LEWIS    2004-06-18 14:15:11
1001     WILSON   2004-06-18 14:16:54
1001     WILSON   2004-06-18 14:21:12
1001     (null)   2004-09-01 09:56:11
1001     CALDONE  2005-02-02 08:38:28
1001     SINCLA   2005-02-02 08:54:02
1002    (null)    2005-02-02 08:40:06
1002     REID     2015-01-16 15:18:05
1002     SMALL    2015-01-16 15:19:53
1002    WILSON    2004-06-18 14:33:47
1002    (null)    2004-08-31 15:12:46
1002    (null)    2004-09-24 10:03:09
1003    RAMSDA    2004-09-24 10:04:24
1003    MOTIKA    2004-08-31 14:51:45
1003    (null)    2004-08-31 15:05:50
1003    MURTHY    2004-09-02 14:50:28
1004    (null)    2004-08-31 15:28:37
1004    (null)    2004-09-24 09:24:21
1005    MOTIKA    2004-08-31 14:47:19
1005    MOTIKA    2004-08-31 17:20:33

我希望输出为-------

ticketid    owner1      owner2      owner3   
1001         43            240        134

owner1值是刘易斯的持续时间(2004-06-18 14:16:54) - (2004-06-18 14:15:11)

拥有者1的值是威尔逊的持续时间(2004-09-01 09:56:11) - (2004-06-18 14:16:54)

1 个答案:

答案 0 :(得分:0)

最后我用完美的输出做了查询。

select ticketid,
owner1=CONVERT(varchar(10),owner2-owner1,108),
owner2=CONVERT(varchar(10),owner3-owner2,108),
owner3=CONVERT(varchar(10),owner4-owner3,108),
owner4=CONVERT(varchar(10),owner4,108)from
(
select ticketid,owndate,'owner'+cast(ROW_NUMBER() over 
(partition by ticketid order by owndate) as varchar(10)) as sno from tkownerhistory                
) tbl
pivot
(
max(owndate)
for sno in(owner1,owner2,owner3,owner4)
)pvt'