我需要获得两个不同行的两次之间的日期差异。我试图操纵这张桌子的ID,但发现了一个死胡同。
表格如下:
ID TimeIn TimeOut EmpId
1 8.30am 12.30pm usr1
2 1.30pm 5.30pm usr1
我需要获得第一行的TimeOut
与第二行的Timein
之间的时差。
预期的输出应该是这样的:
EmpId LunchTime
usr1 1:00
1:00
相当于1小时。
答案 0 :(得分:0)
我怀疑你真正要问的是,"我如何匹配这些值以便比较它们"。一旦你有两个值,比较是微不足道的,但匹配行对不那么简单。查看这篇文章,了解如何解决类似问题:https://www.simple-talk.com/sql/t-sql-programming/solving-complex-t-sql-problems,-step-by-step/
答案 1 :(得分:0)
以下是我的代码并在MYSQL中测试它以供参考。
//EMP table content like below
id TimeIn TimeOut EmpId
1 2015-03-21 09:00:00 2015-03-21 12:30:00 usr1
2 2015-03-21 13:30:00 2015-03-21 17:30:00 usr1
3 2015-03-21 08:00:00 2015-03-21 13:30:00 usr2
4 2015-03-21 14:00:00 2015-03-21 16:00:00 usr2
// find every empId TimeOut of first row and TimeIn of second row
SELECT id,TimeOut ,EmpId,
(select c.TimeIn from EMP c where c.EmpId = a.EmpId and c.id > a.id limit 1) as 'TimeIn'
from EMP a
//result as below
1 2015-03-21 12:30:00 usr1 2015-03-21 13:30:00
2 2015-03-21 17:30:00 usr1 NULL
3 2015-03-21 13:30:00 usr2 2015-03-21 14:00:00
4 2015-03-21 16:00:00 usr2 NULL
//find the timediff between TimeIn and TimeOut
select id,EmpId,timediff(TimeIn,TimeOut) as diff from
(
SELECT id,TimeOut ,EmpId,
(select c.TimeIn from EMP c where c.EmpId = a.EmpId and c.id > a.id limit 1) as 'TimeIn'
from EMP a
) as tmp
// result as below
id EmpId diff
1 usr1 01:00:00
2 usr1 NULL
3 usr2 00:30:00
4 usr2 NULL
希望这可以帮到你。