mysql - 如何使用 GROUP BY 以便按特定列排序?

标签 mysql group-by

我需要从下表中获取所有最新入住时间和退房时间的列表:

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)

SQL Fiddle Demo

关于mysql - 如何使用 GROUP BY 以便按特定列排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31960463/

相关文章:

MySQL 通过 .csv 到 GeoMesa

mysql - GROUP_CONCAT 行到一个字符串

mysql - 内部连接、计数和分组以获得比率

mysql - 在 MySql 中执行查询时与 only_full_group_by 相关的错误

mysql - 触发器复制MySQL中的检查指令?

mysql - 如何使用具有最小字段值的分组来选择行?

PHP SQL : Selecting fields from three tables that are not interlinked

MySQL 使用 GROUP BY 按日期排序

sql-server - 子查询和基本查询 sql server 中的分组依据

php - SQLSTATE[42000] 更新 SQL