1

我只想尝试通过在超过 2 个字段上使用 GROUP BY 来获取最接近的日期时间。但是当我尝试时,数据变得混乱。我正在使用:

数据源是:

Start Time              Real End Time           Staff
2013-02-14 16:44:27     2013-02-14 18:44:27     P 
2013-02-14 16:44:08     2013-02-14 17:09:08     C
2013-02-14 16:42:51     2013-02-14 16:43:51     P
2013-02-14 16:31:26     2013-02-14 17:06:26     V
2013-02-14 16:04:02     2013-02-14 16:34:02     C

当我使用时:

SELECT staff AS name, start_time, max(real_end_time) AS work_end_time
FROM treatments 
WHERE date(real_end_time) = curdate()
GROUP BY name
ORDER BY work_end_time ASC

我得到了:

name        start_time                work_end_time
V           2013-02-14 16:31:26       2013-02-14 17:06:26
C           2013-02-14 16:04:02       2013-02-14 17:09:08
P           2013-02-14 16:42:51       2013-02-14 18:44:27

显然数据乱了,正确的应该是这样的:

name        start_time                work_end_time
V           2013-02-14 16:31:26       2013-02-14 17:06:26
C           2013-02-14 16:44:08       2013-02-14 17:09:08
P           2013-02-14 16:44:27       2013-02-14 18:44:27

为此,它浪费了我很多时间,你应该有好的解决方案吗?我也试过:

SELECT staff AS name, start_time, max(real_end_time) AS work_end_time
FROM treatments 
WHERE date(real_end_time) = curdate()
GROUP BY name, start_time
ORDER BY work_end_time ASC

我得到了:

name     start_time               work_end_time
C        2013-02-14 16:04:02      2013-02-14 16:34:02
P        2013-02-14 16:42:51      2013-02-14 16:43:51
V        2013-02-14 16:31:26      2013-02-14 17:06:26
C        2013-02-14 16:44:08      2013-02-14 17:09:08
P        2013-02-14 16:44:27      2013-02-14 18:44:27
4

1 回答 1

0
SELECT staff AS name, start_time, real_end_time AS work_end_time
FROM (  SELECT staff, start_time, real_end_time
        FROM treatments 
        WHERE date(real_end_time) = curdate()
        ORDER BY real_end_time ASC) AS h
GROUP BY name

您必须使用ORDER BYbefore嵌套查询GROUP BYORDER BY像你一样只处理粉碎在一起的结果,因此有故障和name风险start_time

于 2013-02-14T10:33:11.810 回答