下面的例子是獲取上一年、今年和明年的好辦法嗎?
with cte as(
Select extract(year from sysdate - 365) as year from dual
工會 全部
選擇 提取(年份 from sysdate) as year from double
工會 全部
選擇 提取(年份 from sysdate 365) as year from dual
)
Select * from cte
年月日
-----
2020年
2021 2021
2022 2022
或者有什么更好的解決方案嗎?
uj5u.com熱心網友回復:
好吧,你的不是正確的,例如,閏年的最后一天是該年。看看2020年:
SQL>/span> select
2 extract(year from to_date('31. 12.2020', 'dd.mm.yyyy') - 365) result[/span
3 from dual;
RESULT
----------
20
SQL>
看到了嗎?結果發現,日期31.12.2020的 "前 "年仍然是2020。
ADD_MONTHS是safer,我想:
SQL> select
2 extract (year from add_months(to_date('31. 12.2020', 'dd.mm.yyyy'), 12) result)
3 from dual。
RESULT
----------
2019
SQL>
SQL> select
2 extract (year from add_months(trunc(sysdate), 12) previous,
3 extract (year from add_months(trunc(sysdate), 0) this,
4 extract (year from add_months(trunc(sysdate), 12) next
5 from雙。
上一個 這個 下一個
---------- ----------
2020 2021 2022
SQL>/span>
(this, of course, doesn't require add_months, but I kept it to make query look prettier).
或者,為什么不簡單地
SQL> select this - 1 as previous,
2 this,
3 this 1 as next
4 from (select extract(year from sysdate) as this from dual)。)
上一個 這個 下一個
---------- ----------
2020 2021 2022
SQL>/span>
對于3行,使用CTE:
SQL> with temp(this) as
2 (select extract(year from sysdate) from dual)
3 select this - 1 as year from temp union all
4 select this from temp union all
5 select this 1 from temp;
年 年
----------
2020
2021 2021
2022 2021
SQL>/span>
uj5u.com熱心網友回復:
我可能忽略了一些東西,但為什么不只是這樣呢?
with cte as(
Select extract(year from sysdate) - 1 as year from dual
工會 全部
選擇 提取(年份 from sysdate) as year from double
工會 全部
Select extract(year from sysdate) 1 as year from double
)
Select * from cte
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/306815.html
標籤:
下一篇:sql用觸發器防止重復預訂
