1

我需要比较查询的同一个表中的行。

以下是该表的示例:

id    checkin     checkout    
1     01/15/13    01/31/13
1     01/31/13    05/20/13
2     01/15/13    05/20/13
3     01/15/13    01/19/13
3     01/19/13    05/20/13
4     01/15/13    02/22/13
5     01/15/13    03/01/13

我将结帐日期与今天的日期进行比较,如果它早于今天的日期,那么我想返回结果。但是,和 id 的 1 和 3 类似,它们有多个记录。如果与同一 id 关联的记录之一的结帐日期在今天之后,那么我不想返回他们的任何记录。我只想返回每个 id 的记录,其中每个记录都在结帐字段中的今天日期之前。

4

3 回答 3

1

为此,分析函数是最好的方法:

select id, checkin, checkout
from (select t.*, max(checkout) over (partition by id) as maxco
      from t
     ) t
where maxco <= trunc(sysdate)

这假定数据存储为日期值而不是字符串(否则,最大值将返回错误值)。

于 2013-04-29T21:19:18.283 回答
0
select id, checking  from
Table 
where checkout < CURRENT_DATE --Postgresql date of today, Oracle should have an equivalent now
and id not in (select id from Table where checkout >= CURRENT_DATE);
于 2013-04-29T21:19:38.350 回答
0

这应该为您提供所有在时间之前的记录结果,并且所有具有相同 id 的记录也在时间之前。

SELECT Ta.* 
 FROM TABLE Ta,
      (SELECT MAX(checkout) checkout, ID FROM TABLE GROUP BY ID) Tb
WHERE Ta.ID = Tb.ID 
  AND sysdate >= Ta.checkout -- checks for date in current record
  AND sysdate >= Tb.checkout -- checks for dates in all records 
于 2013-04-29T21:32:09.540 回答