Mysql 在其他值之前选择列的最大值
让我们假设我在MySQL数据库中有一个名为“重定位”的表,我跟踪约会中用户的所有重定位:Mysql 在其他值之前选择列的最大值,mysql,sql,database,Mysql,Sql,Database,让我们假设我在MySQL数据库中有一个名为“重定位”的表,我跟踪约会中用户的所有重定位: UserId AppointmentTypeId History Location Time ------------------------------------------------------ [ 1 1 1 'Room A' 13:00 ] 1 1 2 'Room B'
UserId AppointmentTypeId History Location Time
------------------------------------------------------
[ 1 1 1 'Room A' 13:00 ]
1 1 2 'Room B' 13:01
[ 1 1 3 'Room A' 13:02 ]
1 1 4 'Room C' 13:03
1 1 5 'Room D' 13:05
[ 1 1 6 'Room A' 13:09 ]
2 1 1 'Room A' 13:00
[ 2 1 2 'Room A' 13:05 ]
2 1 3 'Room B' 13:10
我需要得到Location='rooma'的所有行,但只有下一行是Location!='“房间A”和UserId与AppointmentTypeId相同
所以我会从这个表中得到括号内的行
有什么想法吗?您有一个方便的历史记录列,因此请使用左连接:
每次更改的历史记录是否总是连续+1?或者您是否有需要管理的差距?另外,mySQL的哪个版本支持lead或Lag等分析功能?@xQbert historycount始终是连续的-没有间隙。prod server告诉我它运行的是mysql 5.5.43-ubuntu-12.04.1如果它总是按顺序运行,那么我认为Gordon有一个很好的解决方案。该版本不支持窗口/分析功能。
select r.*
from relocations r left join
relocations rnext
on rnext.userid = r.userid and rnext.AppointmentTypeId = r.AppointmentTypeId and
rnext.history = r.history + 1
where r.Location = 'Room A' and
(rnext.Location <> 'Room A' or rnext.Location is null);