简体   繁体   English

Oracle SQL Cursor for循环,用于在START_DATE和END_DATE之间检查并分配行程值

[英]Oracle SQL Cursor for loop to check between the START_DATE and END_DATE and assign a trip value

I'm using SQL Developer for Oracle 11g.. 我正在使用SQL Developer for Oracle 11g。

I need to be able to loop through a set of dates, check to see if the END_DATE above or below is = or < or > than the next END_DATE AND where the START_DATE is different.. 我需要能够遍历一组日期,检查上方或下方的END_DATE是否比下一个END_DATE为=或<或>,且START_DATE不同。

Then assign a trip number that is the same as the one its = to or assign a new trip number and then begin a new trip and check again the next SET of dates to see if its = or < or > than the current date.. 然后,分配一个与其=相同的旅程编号,或分配一个新的旅程编号,然后开始一个新旅程,然后再次检查下一组日期,以查看其=或<或>是否大于当前日期。

I think in order to do this I need to use the pl/sql cursor for loop.. I've tried to figure it out but its not making much sense to me.. 我想为了做到这一点,我需要使用pl / sql游标进行循环..我试图弄清楚它,但对我来说意义不大。

For example, I want the end result to be something like this.. 例如,我希望最终结果是这样的。

ROWID   START_DATE END_DATE   TRIP
  1         30-DEC-11  1-Jan-12 1
  2         31-DEC-11  2-Jan-12 2
  3         31-DEC-11  2-Jan-12 2
  4         01-JAN-12  3-Jan-12 3
  5         03-JAN-12  4-Jan-12 4
  6         01-JAN-12  1-Jan-12 5
  7         02-JAN-12  4-Jan-12 6

Thanks in advance for your help. 在此先感谢您的帮助。 Alex 亚历克斯

Based on the data that you have, you simply want to enumerate the pairs of dates. 根据您拥有的数据,您只想枚举日期对。 You can also do this with dense_rank(): 您也可以使用density_rank()执行此操作:

select t.*,
       dense_rank() over (order by start_date, end_date) as trip
from t

For your data, this will change the ordering. 对于您的数据,这将更改顺序。 If you want to keep roughly the same ordering, then aggregate first, get the min row id, and do a dense_rank() or row_number(), and join back in the original data: 如果要保持大致相同的顺序,请先进行汇总,获取最小行ID,然后执行density_rank()或row_number(),然后重新加入原始数据:

select t.*, trip
from (select start_date, end_date, row_number() over (partition by row_id) as trip
      from (select start_date, end_date, min(rowid) as rowid
            from t
            group by start_date, end_date
           ) a
     ) b join
     t
     on b.start_date = t.start_date and b.end_date = t.end_date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM