我想得到每N最大(日期)< = sysdate。如果过去/今天没有日期,我想要分钟(日期)。所以我不希望绝对日期最接近sysdate。
TESTDATA
CREATE TABLE DATTEST (N NUMBER, D DATE);
INSERT INTO DATTEST (N,D) VALUES (1,TRUNC(SYSDATE-2000));
INSERT INTO DATTEST (N,D) VALUES (1,TRUNC(SYSDATE-1000));
INSERT INTO DATTEST (N,D) VALUES (1,TRUNC(SYSDATE+100));
INSERT INTO DATTEST (N,D)VALUES (2,TRUNC(SYSDATE));
INSERT INTO DATTEST (N,D)VALUES (2,TRUNC(SYSDATE+1000));
INSERT INTO DATTEST (N,D)VALUES (3,TRUNC(SYSDATE+1000));
到目前为止,我已经得到了这个。它给出了正确的结果总线做了两个tablecans。我正在处理大型表,并且多次调用此查询。我一直在打破这个问题,将其转换为单个表扫描。
with nums as
(SELECT LEVEL num
FROM DUAL
CONNECT BY LEVEL <= 3
)
select
num
,(nvl((select max(d)
from dattest
where d <= trunc(sysdate)
and n = num),
(select min(d)
from dattest
where d > trunc(sysdate)
and n = num))
)
from nums;
预期输出
1 26-06-12
2 23-03-15
3 17-12-17
答案 0 :(得分:2)
如何使用聚合,使用一些条件逻辑?
select id,
coalesce(max(case when d <= trunc(sysdate) then d end),
min(d)
)
from table t
group by id;