How to find matching time intervals for more than 2 users

后端 未结 5 1683
自闭症患者
自闭症患者 2021-02-10 06:42

Find best suitable time from given time interval of different users.

Rows: 5
fid  userid  FromDateTime           ToDateTime          flag
62   1   2012-07-18 01:         


        
5条回答
  •  自闭症患者
    2021-02-10 07:32

    To find when both user1 and user2 are free, please try below:

    select 
    a.datetime_start as user1start,a.datetime_end as user1end,
    b.datetime_start as user2start,b.datetime_end as user2end ,
    case when a.datetime_start > b.datetime_start then a.datetime_start 
       else b.datetime_start end as avail_start,
    case when a.datetime_end>b.datetime_end then b.datetime_end 
       else a.datetime_end end as avail_end
    from users a inner join users b on
    a.datetime_start<=b.datetime_end and a.datetime_end>=b.datetime_start     
    and  a.userid={user1} and b.userid={user2}
    

    SQL FIDDLE HERE.

    EDITED: For comparing more than 2 users,pls try below:

    select max(datetime_start) as avail_start,min(datetime_end) as avail_end
    from(
            select *,
            @rn := CASE WHEN @prev_start <=datetime_end and @prev_end >=datetime_start THEN @rn ELSE @rn+1 END AS rn,
            @prev_start := datetime_start,
            @prev_end := datetime_end 
            from(
              select * from users2 m
              where exists ( select null 
                              from users2 o 
                               where o.datetime_start <= m.datetime_end and o.datetime_end >= m.datetime_start
                               and o.id <> m.id 
                            ) 
                 and m.userid in (2,4,3,5)
               order by m.datetime_start) t,
               (SELECT @prev_start := -1, @rn := 1, @prev_end=-1) AS vars 
    ) c 
    group by rn 
    having count(rn)=4 ;
    

    Need to change m.userid in (2,4,3,5) and having count(rn)=4 according to number of users.

    SQL FIDDLE HERE

提交回复
热议问题