SQL ORACLE add 1 second to sysdate every 10 rows

我的未来我决定 提交于 2019-12-23 05:32:53

问题


In dynamic SQL, I'd like to add 1 second every 10 rows

Following query didn't work, got "the interval is invalid"

select 
rownum
,(round(rownum/10,0)+1)
,sysdate + interval '(round(rownum/10,0)+1)' SECOND
from anytable_with_lots_of_rows
where rownum < 100;

Anyone ? thanks !


回答1:


Classic way is the division by the number of seconds in a day, e.g.

with rn as (
select rownum-1 id from dual connect by level <= 100),
rn2 as (select 
id, trunc(id/10) tr_id from rn)
select 
id, tr_id,
sysdate + tr_id / (24*3600) my_date
from rn2;

gives

        ID      TR_ID MY_DATE           
---------- ---------- -------------------
         0          0 28-06-2018 19:05:34 
         1          0 28-06-2018 19:05:34 
         2          0 28-06-2018 19:05:34 
         3          0 28-06-2018 19:05:34 
         4          0 28-06-2018 19:05:34 
         5          0 28-06-2018 19:05:34 
         6          0 28-06-2018 19:05:34 
         7          0 28-06-2018 19:05:34 
         8          0 28-06-2018 19:05:34 
         9          0 28-06-2018 19:05:34 
        10          1 28-06-2018 19:05:35 
        11          1 28-06-2018 19:05:35 
        12          1 28-06-2018 19:05:35 
        13          1 28-06-2018 19:05:35 
        14          1 28-06-2018 19:05:35 
        15          1 28-06-2018 19:05:35 
        16          1 28-06-2018 19:05:35 
        17          1 28-06-2018 19:05:35 
        18          1 28-06-2018 19:05:35

Alternatively, if you want to use intervals - use the function NUMTODSINTERVAL

and replace the division with the following expression

sysdate + NUMTODSINTERVAL(tr_id,'SECOND') my_date 



回答2:


interval <n> second accepts literal numbers only, not arithmetic expressions.

However, you can do this:

....  + (round(rownum/10) + 1) * interval '1' second

or whatever formula you need to get your correct result.

Note that if you want groups of ten rows at a time, you should use "rounding up" (the function ceil()) and not add 1 in parentheses.



来源:https://stackoverflow.com/questions/51088046/sql-oracle-add-1-second-to-sysdate-every-10-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!