在 Oracle 数据库中,可以通过 to_char 对日期进行转换,获得周信息等,以便进行计算。
获取周几信息
例如 2022年9月23日,是星期五:
SQL> select to_char(sysdate,'DY') from dual; TO_CHAR(SYSD ------------ SQL> select sysdate from dual; SYSDATE --------- 23-SEP-22
判断获取周末
更复杂一点的判断:
SQL> select table_name,last_analyzed, case when to_char(last_analyzed,'DY') in ('SAT','SUN') then 'Weekend' end tag from dba_tables where rownum < 20; TABLE_NAME LAST_ANAL TAG ------------------------------ --------- ------- ICOL$ 20-MAR-18 COL$ 10-SEP-22 Weekend IND$ 22-SEP-22 TAB$ 23-SEP-22 CLU$ 22-SEP-22 LOB$ 20-MAR-18 COLTYPE$ 20-MAR-18 SUBCOLTYPE$ 20-MAR-18 NTAB$ 20-MAR-18 REFCON$ 26-JAN-17 OPQTYPE$ 20-MAR-18 TABLE_NAME LAST_ANAL TAG ------------------------------ --------- ------- ICOLDEP$ 20-MAR-18 VIEWTRCOL$ 26-JAN-17 LIBRARY$ 20-MAR-18 ASSEMBLY$ 26-JAN-17 ATTRCOL$ 20-MAR-18 TYPE_MISC$ 20-MAR-18 TS$ 20-MAR-18 FET$ 26-JAN-17 19 rows selected.
通过 ISO-Week,截取,可以找到每个日期所属的周一日期:
SQL> select table_name,last_analyzed,trunc(last_analyzed,'IW') "Monday" from dba_tables where rownum <10; TABLE_NAME LAST_ANAL Monday ------------------------------ --------- --------- ICOL$ 20-MAR-18 19-MAR-18 COL$ 10-SEP-22 05-SEP-22 IND$ 22-SEP-22 19-SEP-22 TAB$ 23-SEP-22 19-SEP-22 CLU$ 22-SEP-22 19-SEP-22 LOB$ 20-MAR-18 19-MAR-18 COLTYPE$ 20-MAR-18 19-MAR-18 SUBCOLTYPE$ 20-MAR-18 19-MAR-18 NTAB$ 20-MAR-18 19-MAR-18
判断某个日期是一周中的周几,另外一个算法:
SQL> select table_name,last_analyzed,trunc(last_analyzed,'IW') "Monday", trunc(last_analyzed)-trunc(last_analyzed,'IW')+1 "Days" from dba_tables where rownum <10; TABLE_NAME LAST_ANAL Monday Days ------------------------------ --------- --------- ---------- ICOL$ 20-MAR-18 19-MAR-18 2 COL$ 10-SEP-22 05-SEP-22 6 IND$ 22-SEP-22 19-SEP-22 4 TAB$ 23-SEP-22 19-SEP-22 5 CLU$ 22-SEP-22 19-SEP-22 4 LOB$ 20-MAR-18 19-MAR-18 2 COLTYPE$ 20-MAR-18 19-MAR-18 2 SUBCOLTYPE$ 20-MAR-18 19-MAR-18 2 NTAB$ 20-MAR-18 19-MAR-18 2