oracle 计算工作日时,周从星期日开始

cwtwac6a  于 2022-12-11  发布在  Oracle
关注(0)|答案(4)|浏览(174)

我试图查找星期日到星期六的工作日。在Oracle中,默认情况下星期一是一周的第一天。因此,当我使用以下查询计算工作日时

Select    to_char(sysdate, 'D')  from dual

由于今天是2022年9月12日,因此结果为5,即从星期一开始一周。我希望这应该计算为从星期日开始一周。理想情况下,如果这周从星期日开始,答案应该是6
有没有什么简单的方法可以做到这一点,我可以用case语句,但这不是一个好的方法。请帮助。

cx6n0qe3

cx6n0qe31#

Talk to your DBA to fix territory. If it was set to e.g. India, then you wouldn't have to calculate anything:

SQL> alter session set nls_territory = 'India';

Session altered.

SQL> Select    to_char(sysdate, 'D') from dual;

T
-
6

SQL>
rta7y2nd

rta7y2nd2#

In Oracle, the first day of a week is determined by NLS_TERRITORY parameter. So use a value of NLS_TERRITORY where Sunday is the first weekday, for example, AMERICA .

alter session set nls_territory=RUSSIA
select to_char(sysdate, 'D')
from dual
TO_CHAR(SYSDATE,'D')
5
alter session set nls_territory=AMERICA
select to_char(sysdate, 'D')
from dual
TO_CHAR(SYSDATE,'D')
6

fiddle

dwthyt8l

dwthyt8l3#

Option 1: NLS_TERRITORY session parameter

In Oracle, the day of the week depends on the NLS_TERRITORY session setting:

SELECT TO_CHAR(DATE '2022-12-11', 'D') AS day, -- a sunday
       (SELECT value FROM NLS_SESSION_PARAMETERS WHERE parameter = 'NLS_TERRITORY')
         AS territory
FROM   DUAL;

Outputs different values for different parameters. I.e., if you use:

ALTER SESSION SET NLS_TERRITORY='America';
ALTER SESSION SET NLS_TERRITORY='Germany';
ALTER SESSION SET NLS_TERRITORY='India';
ALTER SESSION SET NLS_TERRITORY='Oman';
ALTER SESSION SET NLS_TERRITORY='Bangladesh';

and run the query for each then the outputs are:
| DAY | TERRITORY |
| ------------ | ------------ |
| 1 | AMERICA |
| 7 | GERMANY |
| 1 | INDIA |
| 2 | OMAN |
| 3 | BANGLADESH |
So you could just pick the correct territory for your database, i.e.:

ALTER SESSION SET NLS_TERRITORY='India';

Option 2: Compare to the start of the ISO-week

Or if you want to be independent of the session settings then you can compare it to the start of the ISO-week (which is always midnight Monday) and offset by one day to change the comparison from Monday-Sunday to Sunday-Saturday:

SELECT TRUNC(SYSDATE + 1) - TRUNC(SYSDATE + 1, 'IW') + 1 AS day
FROM   DUAL;

Which, for today (Friday) outputs:
| DAY |
| ------------ |
| 6 |
fiddle

lawou6xi

lawou6xi4#

我找到了这个问题的答案,非常简单

select mod(to_char(sysdate,'D'),7)+1 as Weekday from Dual

相关问题