我有下表robot_state:
section robotid date active
area1| 11 | 2014-08-09 02:40:09 | 1
area1| 11 | 2014-08-09 02:55:50 | 0
area3| 01 | 2014-08-09 03:40:09 | 1
area3| 11 | 2014-08-10 00:15:50 | 1
area1| 11 | 2014-08-10 02:40:09 | 1
area1| 11 | 2014-08-12 00:15:50 | 0
对于特定部分和机器人ID,我想使用两个单独的列提取机器人处于活动状态和非活动状态的日期。例如,对于区域1和
robotid = 11,我应该得到这个结果:
robot_ON | robot_OFF 2014-08-09 02:40:09 | 2014-08-09 02:55:50 2014-08-10 02:40:09 | 2014-08-12 00:15:50
任何帮助我如何编写查询。我尝试过工会:
select date from robot_state where (active=1 and section ='area1' and robotid=11)
union
select date from robot_state where (active=0 and section ='area1' and robotid=11);
但结果显示在一列中。有两列的想法是稍后计算机器人每次开始工作时的时差。
答案 0 :(得分:0)
尝试将robot_state连接到自身,这些内容(我还没试过)
select on.date, off.date from (
select date
from robot_state
where active=1 and section ='area1' and robotid=11
) as On
inner join (
select date
from robot_state
where active=0 and section ='area1' and robotid=11
) as off
on off.date = (select min(date)
from robot_state
where active=0 and section ='area1' and robotid=11
and date > on.date)