![](/img/trans.png)
[英]Oracle SQL - get number of days between two dates for a specified month
[英]Getting unexpected values for number of days between two dates in oracle
我正在編寫一個 SQL 代碼,它從數據庫中獲取兩個日期並計算它們之間的天數。 這是代碼:
create table borrower(
roll_no number,
date_of_issue date,
name_of_book varchar(20),
status varchar(10)
);
insert into borrower values(1,to_date('02-JAN-2022'),'dbms','issued');
insert into borrower values(2,to_date('10-JAN-2022'),'cns','issued');
insert into borrower values(3,to_date('17-JAN-2022'),'spos','issued');
insert into borrower values(4,to_date('26-JAN-2022'),'toc','issued');
create table fine(
roll_no number,
current_date date,
amount number
);
insert into fine values(1,to_date('14-FEB-2022'),null);
insert into fine values(2,to_date('14-FEB-2022'),null);
insert into fine values(3,to_date('14-FEB-2022'),null);
insert into fine values(4,to_date('14-FEB-2022'),null);
DECLARE
roll_counter number:=1;
initial_date date;
final_date date;
date_calc number;
BEGIN
loop
select date_of_issue into initial_date from borrower where roll_no=roll_counter;
select current_date into final_date from fine where roll_no=roll_counter;
date_calc:=final_date-initial_date;
dbms_output.put_line(date_calc);
roll_counter:=roll_counter+1;
exit when roll_counter>4;
end loop;
END;
/
drop table borrower;
drop table fine;
我沒有收到任何錯誤,而是收到了天數的意外值。 這是 output:
Statement processed.
246.4165625
238.4165625
231.4165625
222.4165625
我期待兩個日期之間的天數(查看表格)。 有人可以幫我解決這個問題。
CURRENT_DATE
是返回當前日期的 Oracle 關鍵字。 將您的列命名為不是 Oracle 關鍵字的名稱。
正如@Matthew McPeak 指出的那樣, CURRENT_DATE
是一個內置的 function 並且正在調用 function 而不是返回您的列值。
如果你想要列值,那么你需要在列名前加上表名/別名並使用fine.current_date
:
DECLARE
roll_counter number:=1;
initial_date date;
final_date date;
date_calc number;
BEGIN
FOR roll_counter IN 1 .. 4 LOOP
select date_of_issue
into initial_date
from borrower
where roll_no=roll_counter;
select fine.current_date
into final_date
from fine
where roll_no=roll_counter;
date_calc:=final_date-initial_date;
dbms_output.put_line(date_calc);
END LOOP;
END;
/
其中,對於您的樣本數據,輸出:
43 35 28 19
或者您可以使用單個查詢(而不是在每次循環迭代中調用的多個查詢):
BEGIN
FOR r IN (
SELECT f.current_date - b.date_of_issue AS diff
FROM borrower b
FULL OUTER JOIN fine f
ON (b.roll_no = f.roll_no)
WHERE COALESCE(b.roll_no, f.roll_no) BETWEEN 1 AND 4
ORDER BY COALESCE(b.roll_no, f.roll_no)
) LOOP
dbms_output.put_line(r.diff);
END LOOP;
END;
/
db<> 在這里擺弄
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.