暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 如何找出日期是周末还是工作日

askTom 2017-05-01
669

问题描述

大家好,

我很难弄清楚如何从专栏中找出日期是工作日还是周末。

场景

创建表A
(a_id VARCHAR2(20),
日期默认系统日期,
约束A_PK主键 (a_id));

表A有一些随机日期


创建表B
(b_id VARCHAR2(20),
日期 _ desc VARCHAR2(20),
约束B_PK主键 (b_id));

现在我该如何确定date_a是一个工作日或周末,甚至像元旦这样的假期,然后使用PL/SQL块生成表B的date_desc的结果?

任何例子都值得赞赏。

谢谢大家

专家解答

SQL> CREATE TABLE t
  2  (id int,
  3   d date);

Table created.

SQL>
SQL> insert into t
  2  select rownum, trunc(sysdate) -10 + rownum
  3  from dual
  4  connect by level <= 20;

20 rows created.

SQL>
SQL> select *
  2  from t;

  ID D
---- ---------
   1 23-APR-17
   2 24-APR-17
   3 25-APR-17
   4 26-APR-17
   5 27-APR-17
   6 28-APR-17
   7 29-APR-17
   8 30-APR-17
   9 01-MAY-17
  10 02-MAY-17
  11 03-MAY-17
  12 04-MAY-17
  13 05-MAY-17
  14 06-MAY-17
  15 07-MAY-17
  16 08-MAY-17
  17 09-MAY-17
  18 10-MAY-17
  19 11-MAY-17
  20 12-MAY-17

20 rows selected.

SQL>
SQL> select id, d,
  2   case when to_char(d,'DY') in ('SAT','SUN') then 'Weekend' end tag
  3  from t;

  ID D         TAG
---- --------- -------
   1 23-APR-17 Weekend
   2 24-APR-17
   3 25-APR-17
   4 26-APR-17
   5 27-APR-17
   6 28-APR-17
   7 29-APR-17 Weekend
   8 30-APR-17 Weekend
   9 01-MAY-17
  10 02-MAY-17
  11 03-MAY-17
  12 04-MAY-17
  13 05-MAY-17
  14 06-MAY-17 Weekend
  15 07-MAY-17 Weekend
  16 08-MAY-17
  17 09-MAY-17
  18 10-MAY-17
  19 11-MAY-17
  20 12-MAY-17

20 rows selected.

SQL>
SQL> create table pub_hols ( ph date , why varchar2(20));

Table created.

SQL>
SQL> insert into pub_hols values ( date '2017-05-01', 'May Day');

1 row created.

SQL>
SQL>
SQL> select id, d,
  2   case when to_char(d,'DY') in ('SAT','SUN') then 'Weekend' end tag,
  3   why
  4  from t,
  5       pub_hols
  6  where t.d = pub_hols.ph(+)
  7  order by 2;

  ID D         TAG     WHY
---- --------- ------- --------------------
   1 23-APR-17 Weekend
   2 24-APR-17
   3 25-APR-17
   4 26-APR-17
   5 27-APR-17
   6 28-APR-17
   7 29-APR-17 Weekend
   8 30-APR-17 Weekend
   9 01-MAY-17         May Day
  10 02-MAY-17
  11 03-MAY-17
  12 04-MAY-17
  13 05-MAY-17
  14 06-MAY-17 Weekend
  15 07-MAY-17 Weekend
  16 08-MAY-17
  17 09-MAY-17
  18 10-MAY-17
  19 11-MAY-17
  20 12-MAY-17

20 rows selected.

SQL>
SQL>


在使用诸如 “SUN” 之类的文字时,请仔细检查,因为它将取决于您的nls设置。
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论