繁体   English   中英

SQL-查找满足条件的所有ID的ID

[英]SQL - find id for all ids that meet condition

我正在尝试SQL查询以下数据库:

试图找出我的系统中的错误,该错误正在跟踪进入和退出我的龙门架的以下人员。 从技术上讲,您必须先退出,然后才能有另一个条目。 所以我试图找到退出时间早于下一次进入的用户。 我们忽略退款,退出时间为空白

查找每个用户的r_id (receipt_ID),当前的date_time_out (退出时)位于下一个收据的date_time_in (再次进入时)之前。 我需要为这些用户返回他们所有的唯一收据ID,因为这些都是错误的。

示例数据库:

r_id | user_id |  date_time_in | date_time_out   | date_time_refund

0001 | 12345   | 21/02/19 01:00| 23/02/19 01:12

0002 | 12345   | 21/02/19 01:10| 23/02/19 01:15

0003 | 12345   | 21/02/19 01:16| 23/02/19 01:17

0009 | 12346   | 21/02/19 01:02| _____Null______ | 23/02/19 01:03

0010 | 12346   | 21/02/19 01:02| 23/02/19 01:03

预期输出(升序):

0001

0002

你可以使用自我加入

select a.r_id , b.r_id
from my_table a 
inner join my_table b on a.user_id = b.user_id 
        and a.date_time_out > b.date_time_in 
        and a.date_time_out is nul null 
order by a.r_id asc 

或用于分隔行

  select * from my_table  m 
  inner join  
  (
      select a.r_id id1 , b.r_id id2
      from my_table a 
      inner join my_table b on a.user_id = b.user_id 
              and a.date_time_out > b.date_time_in 
              and a.date_time_out is nul null 
  ) t on m.r_id = t.id1 or m.r_id = id2 
  order by m.r_id asc 

假设r_id正在捕获记录的序列,则使用exists

select e.*
from example e
where exists (select 1
              from example e2
              where e2.user_id = e.user_id and
                    e2.r_id > e.r_id and
                    e2.date_time_in < e.date_time_out
             ) or
      exists (select 1
              from example e2
              where e2.user_id = e.user_id and
                    e2.r_id < e.r_id and
                    e2.date_time_in > e.date_time_out
             );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM