2

我必须对表中的这些列进行一些分析: Id, UserName, DateFrom, DateTo. 我必须找出用户在同一时间段内有多个条目。我想知道是否有一种方法可以在单个 Select 语句中执行此操作?.....否则我想不出比存储过程更好的方法...有人可以帮助我提供一些想法和提示。

Id----------UserId-------------DateFrom------------DateTo
1-----------Tim123-------------------- 11/19/2012 08:00---11/19/2012 11:00
2-----------Tim123-------------------- 11/19/2012 10:00---11/19/2012 11:00
3-----------Tim123-------------------- 11/19/2012 12:00---11/19/2012 17:00
1-----------John123--------------------11/19/2012 08:00---11/19/2012 11:00
4

3 回答 3

5
sqlite> insert into user_data values(1, "john", "12-nov-12", "25-nov-12");
sqlite> insert into user_data values(2, "john", "24-nov-12", "25-dec-12");
sqlite> insert into user_data values(3, "jack", "12-nov-12", "25-nov-12");
sqlite> insert into user_data values(4, "jack", "26-nov-12", "30-nov-12");

sqlite> select distinct ud1.userid 
        from user_data ud1, user_data ud2
        where ud1.userid = ud2.userid 
              and ud1.datefrom <= ud2.dateto and ud2.datefrom <= ud1.dateto
              and ud1.id < ud2.id;
john

这个想法是

  • 如果周期 A 在周期 B 结束之前开始
  • 期间 A 在期间 B 开始后结束

然后有重叠。

于 2012-11-19T22:16:22.170 回答
1
select * 
from mytable t1
join mytable t2 
    on t1.UserName = t2.username
    and t1.DateFrom <= t2.DateTo -- this is how to check for any overlap
    and t1.DateTo >= t2.DateFrom -- this is how to check for any overlap
    and t1.id < t2.id -- don't join to self, which would otherwise match
于 2012-11-19T21:57:59.613 回答
-1

您可以使用嵌套查询和 COUNT 来跟踪出现次数

 SELECT t1.id, t1.UserName, t1.DateFrom, t1.DateTo
 FROM your_table_name t1
 WHERE (SELECT COUNT(*) 
 FROM your_table_name t2 
 WHERE t1.DateFrom=t2.DateFrom 
 AND t1.DateTo = t2.DateTo)>1
于 2012-11-19T21:58:11.407 回答