根据日期选择活动/非活动

时间:2016-09-15 11:00:20

标签: sql oracle

我有以下表格:

表TRANSACTION

ID   | DATE  
----   ------
1    | 23-01-16
2    | 23-01-16
1    | 24-01-16

表USER_ID

 ID
----
1
2

现在的问题是,在日期范围23-01-16和25-01-16之间,如何检测2在24-01-16处于非活动状态,1,2在25-01-16处处于非活动状态

如果我正在使用

select u.id 
from user_id u 
where u.user_id not in (select t.id 
                        from transaction t 
                        where t.date>='23-01-16' 
                        and t.date<='25-01-16') 

我会在该范围之间获得非活动ID,但不会根据具体日期。

关于如何做的任何想法。

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

select user_id.id, day
from user_id
     cross join (
                select date '2016-01-23' + level -1 as day
                from dual
                connect by  date '2016-01-23' + level -1 <= date '2016-01-25'
                ) days
     left outer join transaction_ on ( user_id.id_ = transaction.id and
                                       days.day = transaction.date
                                     )
where transaction.date is null

connect by的部分根据您输入的间隔(23-25 / 01)建立一个天数列表;其余部分使用外部联接来仅检查缺失的事件。