我如何匹配这些值以便比较它们
how do I match up the values in order to compare them
我需要获取两个不同行的两个时间之间的日期差。我试图操纵这个 table 的 ID,但发现了死胡同。
table 看起来像这样:
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小时。
我怀疑你真正想问的是,"how do I match up the values in order to compare them"。一旦您拥有两个值,比较就很简单了,但是匹配行对就不那么简单了。查看这篇文章,了解如何解决类似问题的几乎精确的步骤:https://www.simple-talk.com/sql/t-sql-programming/solving-complex-t-sql-problems,-step-by-step/
以下是我的代码,在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
希望对您有所帮助。
我需要获取两个不同行的两个时间之间的日期差。我试图操纵这个 table 的 ID,但发现了死胡同。
table 看起来像这样:
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小时。
我怀疑你真正想问的是,"how do I match up the values in order to compare them"。一旦您拥有两个值,比较就很简单了,但是匹配行对就不那么简单了。查看这篇文章,了解如何解决类似问题的几乎精确的步骤:https://www.simple-talk.com/sql/t-sql-programming/solving-complex-t-sql-problems,-step-by-step/
以下是我的代码,在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
希望对您有所帮助。