[英]SQL Oracle - Using RowNum in Query
我有两个表,示例如下。
table_1
days special_day
10/09/2013 Y
10/10/2013 N
10/11/2013 Y
10/12/2013 N
10/13/2013 N
10/14/2013 Y
table_2
id special_day_ind numdays order
123 Y 3 2
456 N 5 1
我的查询将不得不基于table_2中的参数从table_1中选择sysday和正确日期之间的差异。 如果special_day_ind为'Y',那么我需要从sysdate返回3(numdays)special_days。 如果为“ N”,答案就是数字。 结果将按顺序升序(结束)进行ORDER(ed)。
在上面的表格示例中,查询将返回。
sysdate = 10/14/2013
id days
456 5
123 5 (10/14/2013 - 10/9/2013)
看起来ROWNUM可以解决问题,但是由于计数的“方式”不同,我不确定如何进行。
这是一种方法。
您需要为table_1中的特殊日期分配行号。
select days,
row_number() over (order by days desc) r
from table_1
where special_day = 'Y';
使用此作为CTE,您可以找到较早的特殊日子并将其从sysdate中减去。
with x as(
select days,
row_number() over (order by days desc) r
from table_1
where special_day = 'Y'
)
select id,
case when special_day_ind = 'N'
then numdays
when special_day_ind = 'Y'
then trunc(sysdate) - (select days
from x
where r = numdays)
end days
from table_2
order by order_;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.