我需要从下表中获取所有最新入住时间和退房时间的列表:
Table: checkin_times
+----------+-------------------------+---------------------+
| Person | in_time | out_time |
+----------+-------------------------+---------------------+
| Bob | 2015-08-10 07:15:00 | 2015-08-10 17:15:00 |
| Bob | 2015-08-12 07:00:00 | NULL |
| Geoff | 2015-08-12 07:40:00 | 2015-08-12 17:40:00 |
| Bob | 2015-08-11 07:15:00 | 2015-08-12 17:15:00 |
| Geoff | 2015-08-10 07:00:00 | 2015-08-12 17:00:00 |
+----------+-------------------------+---------------------+
(显然 NULL
表示此人尚未 checkout 。)
我对最新条目不感兴趣。因此,对于这个例子,输出应该是:
+----------+-------------------------+---------------------+
| Person | in_time | out_time |
+----------+-------------------------+---------------------+
| Bob | 2015-08-12 07:00:00 | NULL |
| Geoff | 2015-08-12 07:40:00 | 2015-08-12 17:40:00 |
+----------+-------------------------+---------------------+
我尝试了以下 SQL:
SELECT person, MAX(in_time) AS in_time, MAX(out_time) AS out_time
FROM checkin_times
GROUP BY person
ORDER BY person;
但它无法正确处理 NULL
,而是返回 out_time
的最新实际日期。
理想情况下,我希望 GROUP BY 的顺序仅在确定顺序时才考虑 in_time
。
最佳答案
如果我理解正确,您正在尝试获取每个人最新 in_time 的所有列值。
然后首先获取最新的in_time并将它们连接到所有记录上。
示例:
mysql> select ct.person, ct.in_time, ct.out_time
-> from checkin_times ct
-> right join ( select person, max( in_time ) as in_time
-> from checkin_times group by person ) it
-> on ct.person = it.person and ct.in_time=it.in_time;
+--------+---------------------+---------------------+
| person | in_time | out_time |
+--------+---------------------+---------------------+
| Bob | 2015-08-12 07:00:00 | NULL |
| Geoff | 2015-08-12 07:40:00 | 2015-08-12 17:40:00 |
+--------+---------------------+---------------------+
2 rows in set (0.04 sec)
关于mysql - 如何使用 GROUP BY 以便按特定列排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31960463/