MySQL查询-一个表-一天之内找到两个日期-来自不同列+差异计算的同一实体

时间:2019-03-19 09:41:34

标签: mysql time diff

我试图通过一个mysql查询来计算包含办公室内外人员的表。

我所拥有的:

id  PERSON      IN                  OUT
1   Person A    2019-03-11 08:59:30 NULL
2   Person B    2019-03-11 08:32:00 NULL
3   Person C    2019-03-11 08:04:40 NULL
4   Person D    2019-03-11 07:58:50 NULL
5   Person E    2019-03-11 07:35:20 NULL
6   Person F    2019-03-11 07:35:00 NULL
7   Person A    NULL                2019-03-11 15:00:50
8   Person B    NULL                2019-03-11 14:57:00
8   Person C    NULL                2019-03-11 13:19:50
9   Person D    NULL                2019-03-11 15:14:20
10  Person E    NULL                2019-03-11 15:15:50
11  Person F    NULL                2019-03-11 15:28:10

我想要得到什么:

id  PERSON      IN                  OUT                 DIFF IN MINUTES
1   Person A    2019-03-11 08:59:30 2019-03-11 15:00:50 XXX
2   Person B    2019-03-11 08:32:00 2019-03-11 14:57:00 XXX
3   Person C    2019-03-11 08:04:40 2019-03-11 13:19:50 XXX
4   Person D    2019-03-11 07:58:50 2019-03-11 15:14:20 XXX
5   Person E    2019-03-11 07:35:20 2019-03-11 15:15:50 XXX
6   Person F    2019-03-11 07:35:00 2019-03-11 15:28:10 XXX
                                                        TOTAL OF XXXS
                                                        TOTAL OF XXXS - YYY (constant)

该想法是获取一天中在办公室花费的时间的信息。此外,我需要每人整个月的会议记录摘要。每人/每月分组。

我花了一些时间,并且使用了此查询,但是效果中等:

SELECT a.PERSON, a.IN, b.OUT, TIMESTAMPDIFF(SECOND,a.IN,b.OUT)-28880 AS WHATSLEFT
FROM presence a
INNER JOIN presence b
ON a.PERSON = b.PERSON
WHERE DATEDIFF(a.IN,b.OUT) = 0 AND b.PERSON ="Person A"
ORDER BY a.IN;

感谢您的帮助! 亚当

2 个答案:

答案 0 :(得分:0)

您可以从这里开始:

SELECT a.PERSON, a.IN, b.OUT, TIMESTAMPDIFF(SECOND, a.IN, b.OUT) AS TOTAL
FROM presence a
LEFT JOIN presence b ON b.id = (
  SELECT MIN(b2.id)
  FROM presence b2
  WHERE b2.PERSON = a.person
    AND b2.id > a.id
    AND b2.OUT IS NOT NULL
)
WHERE a.IN IS NOT NULL
ORDER BY a.IN;

它将返回:

PERSON      IN                      OUT                     TOTAL
-----------------------------------------------------------------
Person F    2019-03-11 07:35:00     2019-03-11 15:28:10     28390
Person E    2019-03-11 07:35:20     2019-03-11 15:15:50     27630
Person D    2019-03-11 07:58:50     2019-03-11 15:14:20     26130
Person C    2019-03-11 08:04:40     2019-03-11 13:19:50     18910
Person B    2019-03-11 08:32:00     2019-03-11 14:57:00     23100
Person A    2019-03-11 08:59:30     2019-03-11 15:00:50     21680

Demo

查询将在IN中具有值的行与同一人在OUT中具有值的下一行合并。假设id是一个AUTO_INCREMENT主键,并且您的数据正确。

您现在可以将其更改为GROUP BY查询。

答案 1 :(得分:0)

对保罗每天提供的分钟查询的改进是:

onTextChanged

DEMO DAY

对飞蛾的查询如下:

SELECT 
    a.PERSON, 
    a.IN, 
    b.OUT, 
    TIMESTAMPDIFF(MINUTE,a.IN,b.OUT) AS `DIFF IN MINUTES`
FROM presence a
INNER JOIN presence b ON ( a.PERSON = b.PERSON )
WHERE DAY(a.IN) = DAY(b.OUT)
ORDER BY a.IN;

DEMO MONTH