Mysql在两列中使用相同的表行

时间:2016-11-21 20:28:56

标签: mysql

我有一个名为Notifications的表,其中status = 1是EntryTime,status = 2是ExitTime。

  +-----+------+------+------+--------+
  | n_id| notification_time   | status | 
  +-----+------+------+------+--------+
  |  1  | 2016-11-17 16:44:02 |   2    |
  |  1  | 2016-11-17 16:43:55 |   1    |
  |  2  | 2016-11-17 13:05:47 |   1    |
  |  2  | 2016-11-17 13:08:29 |   2    |
  |  4  | 2016-11-17 14:09:02 |   1    |
  |  4  | 2016-11-17 14:13:45 |   2    |
  |  1  | 2016-11-17 22:05:02 |   1    |
  |  1  | 2016-11-17 22:09:12 |   2    |
  +----+------+------+-------+---------+

我需要像

这样的结果
  +-----+------+------+------+--------+--------+--------+
  | n_id| Entry_time          | Exit_time               | 
  +-----+------+------+------+--------+--------+--------+
  |  1  | 2016-11-17 16:43:55 |   2016-11-17 16:44:02   |
  |  2  | 2016-11-17 13:05:47 |   2016-11-17 13:08:29   |
  |  4  | 2016-11-17 14:09:02 |   2016-11-17 14:13:45   | 
  |  1  | 2016-11-17 22:05:02 |   2016-11-17 22:09:12   |
  +----+------+------+-------+---------+-------+--------+

有关如何执行此操作的任何建议?非常感谢!

2 个答案:

答案 0 :(得分:2)

您可以尝试分组:

select n_id
    , min(notification_time) as entry_time
    , max(notification_time) as exit_time
from Notifications
group by n_id

答案 1 :(得分:1)

如果你总是有几个不同的n_id,你可以使用基于别名的sellf连接

  select a.n_id, a.notification_time as Entry_time, a.notification_time as Exit_time
  from my_table a 
  inner join my_table b on a.n_id = b.n_id
  where a.status = 1
  and b.status = 2

如果n_id是重复的,则需要其他列来实现行之间的正确匹配