【问题标题】:Extract from the same column different queries , resuls are diplayed in separate columns从同一列中提取不同的查询,结果显示在不同的列中
【发布时间】:2014-10-23 19:27:51
【问题描述】:

我有下表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,我想使用两个单独的列提取机器人处于活动状态和非活动状态的日期。例如对于区域 area1 和

robotid=11,我应该得到这个结果:

机器人_ON |机器人_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);

但结果显示在一列中。有两列的想法是稍后计算机器人在每次开始工作时处于活动状态的时间差。

【问题讨论】:

    标签: database postgresql join union


    【解决方案1】:

    尝试自行加入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)
    

    【讨论】:

    • 非常感谢,我试过了,除了“on.date”和“off.date”不被接受,我用了robotOn.date和robotOff.date。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 2019-08-08
    相关资源
    最近更新 更多