日期:2014-05-17 浏览次数:20629 次
select a.id,a.time as Intime, b.Time as OutTime,
datediff(ss/*以秒记*/,a.time,b.time) as LT
from tb a cross apply
(select top (1)* from tb b where a.ID = b.ID and b.time > a.time
and b.device = 2 order by b.time desc)p
where a.device = 1
WITH test (id,TIME,device)
AS
(
SELECT 1,'2012-09-23 12:10:01',1
UNION ALL
SELECT 1,'2012-09-24 12:10:01',2 --模拟跨天
UNION ALL
SELECT 2,'2012-09-23 12:10:01',1
UNION ALL
SELECT 2,'2012-09-23 14:10:01',2 --模拟当天
)
--SELECT * FROM test
SELECT id,InTime=MAX(CASE WHEN device=1 THEN TIME END ),OutTime=MAX(CASE WHEN device=2 THEN TIME END ),
CASE WHEN DATEPART(DAY,MAX(CASE WHEN device=1 THEN TIME END ))=DATEPART(DAY,MAX(CASE WHEN device=2 THEN TIME END ))
THEN CONVERT(VARCHAR(10),DATEDIFF (hh,MAX(CASE WHEN device=1 THEN TIME END ),MAX(CASE WHEN device=2 THEN TIME END)))+'小时'
+ CONVERT(VARCHAR(10),DATEDIFF (mi,DATEPART(mi,MAX(CASE WHEN device=1 THEN TIME END )),DATEPART(mi,MAX(CASE WHEN device=2 THEN TIME END))))
+'分'+CONVERT(VARCHAR(10),DATEDIFF (ss,DATEPART(ss,MAX(CASE WHEN device=1 THEN TIME END )),DATEPART(ss,MAX(CASE WHEN device=2 THEN TIME END))))+'秒'
ELSE CONVERT(VARCHAR(10),DATEDIFF (hh,MAX(CASE WHEN device=1 THEN TIME END ),MAX(CASE WHEN device=2 THEN TIME END)))+'小时'
+ CONVERT(VARCHAR(10),DATEDIFF (mi,DATEPART(mi,MAX(CASE WHEN device=1 THEN TIME END )),DATEPART(mi,MAX(CASE WHEN device=2 THEN TIME END))))
+'分'+CONVERT(VARCHAR(10),DATEDIFF (ss,DATEPART(ss,MAX(CASE WHEN device=1 THEN TIME END )),DATEPART(ss,MAX(CASE WHEN device=2 THEN TIME END))))+'秒'
END
FROM test
GROUP BY id
/*
----------- ------------------- ------------------- --------------------------------------
1 2012-09-23 12:10:01 2012-09-24 12:10:01 24小时0分0秒
2 2012-09-23 12:10:01 2012-09-23 14:10:01 2小时0分0秒
警告: 聚合或其他 SET 操作消除了 Null 值。
(2 行受影响)
*/