显示小于特定日期但在其余数据组中最大的最大日期

时间:2019-02-14 08:59:35

标签: sql oracle

我在表中设置了具有ID和时间的行,我试图获取时间少于所提到的特定时间的行,同时所选行应在其余行中最多。

我已经创建了一个临时表并向其中添加了ID和相应的日期,现在我试图将表中的日期与特定日期进行比较,同时在select中选择ID和Max Date,但不幸的是,我得到了多行,相反,我要在提到的特定时间之后寻找时间最长的行

create table temp_test (id varchar2(20),tmstmp date);

在下面的查询中随机插入数据

insert into temp_test values (10, sysdate);

选择查询的输出为

ID      TMSTMP
--  -------------------
15  2019-02-15 20:29:31
10  2019-02-15 20:25:51
11  2019-02-15 20:26:00
12  2019-02-15 20:26:08
13  2019-02-15 20:26:16
10  2019-02-15 20:26:22

现在我正在尝试执行以下查询

select id, max(TMSTMP) from temp_test
where TMSTMP <  TO_DATE('2019-02-15 20:28:00', 'YYYY-MM-DD HH24:MI:SS')
group by id;

获得的结果就像-实际结果

ID      TMSTMP
--  -------------------
13  2019-02-15 20:26:16
11  2019-02-15 20:26:00
12  2019-02-15 20:26:08
10  2019-02-15 20:26:22

但是我希望获得如下所示的输出,因为这是指定时间之后的最长时间

ID      TMSTMP
--  -------------------
10  2019-02-15 20:26:22

真的很感谢其他解决方案,谢谢

小编修改为约翰的答案,

如果我还有另一列说名称,并且想在示例上应用过滤器,该怎么办;

select *
from temp_test
where name ='TOM' and tmstmp = (select max(tmstmp) 
            from temp_test 
            where name ='TOM' and tmstmp < TO_DATE('2019-02-15 20:28:00', 
'YYYY-MM-DD HH24:MI:SS'))

在这里是否可以删除重复的比较?

1 个答案:

答案 0 :(得分:2)

我假设您希望整个行都在最大日期之前加上最大时间戳:

with CTE as
(
select id, tmstmp, row_number() over (order by tmstmp desc) as rn
from temp_test
where tmstmp < TO_DATE('2019-02-15 20:28:00', 'YYYY-MM-DD HH24:MI:SS')
)
select *
from CTE
where rn = 1

select *
from temp_test
where tmstmp = (select max(tmstmp) 
                from temp_test 
                where tmstmp < TO_DATE('2019-02-15 20:28:00', 'YYYY-MM-DD HH24:MI:SS'))

如果按ID分组,则max(tmstmp)将是每个给定ID(分组)的最大值