我只是想在两个以上的字段上使用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
答案 0 :(得分: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 BY
之前,您必须使用GROUP BY
嵌套查询。像{1}}那样只处理破碎的结果,因此存在错误的风险ORDER BY
和name