我有一些桌子
CREATE TABLE receptions (
id int(11) AUTO_INCREMENT,
personID int(11),
manager varchar(255),
timestamp datetime DEFAULT CURRENT_TIMESTAMP,
flag tinyint(1),
);
想要获得行WHERE flag = 1
,如
id | personID | "last_manager" | "last_timestamp" | "prev_manager" | "prev_timestamp"
3 | 1 | manager2 | 01.11.2017 11:00:23 | manager1 | 01.11.2017 10:00:00
6 | 2 | manager3 | 01.11.2017 14:00:00 | manager3 | 01.11.2017 13:00:23
......等等。抱歉格式化。
是否可以使用单一查询来获取这种格式的数据?
答案 0 :(得分:0)
注意:我还没有尝试过 - 请提供示例数据和预期结果,最好是作为SQLFiddle。但本质上是一个自我连接,MAX可以找到最新的和最新的一行。
select last.id,
last.personID,
last.manager as last_manager,
max(last.timestamp) as "last_timestamp",
previous.manager as "prev_manager",
max(previous.timestamp) as "prev_timestamp"
from receptions last
inner join receptions previous on previous.personid = last.personid
where last.timestamp > previous.timestamp
and last.flag = 1
group by last.id,
last.personID
Here'是一个SQLFiddle。