[英]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.