计算两个日期之间的工作日Oracle

时间:2018-12-17 11:57:15

标签: sql oracle

我正在尝试编写一个查询,该查询可以计算收到的付款和正在处理的付款之间的工作日数,我开始处理2017年12月收到的付款;

select unique trunc(date_received), 
   (case when trunc(date_received) in ('25-DEC-17','26-DEC-17') Then 0 when 
to_char(date_received,'D') <6 Then 1 else 0 end) Working_day
from payments
where date_received between '01-DEC-17' and '31-dec-17'
order by trunc(date_received) 

但是,老实说,我对如何进一步使用它并添加date_processed以及计算介于date_processed和date_received之间的工作日数感到迷惑...非常感谢您的帮助...

1 个答案:

答案 0 :(得分:2)

也许不是最佳选择,但效果很好,并且很容易合并更复杂的支票,例如假期。该查询首先生成两个日期之间的所有日期,然后让您过滤掉所有“不计算在内”的日期。

在此实现中,我仅过滤了周末,但是添加假期等检查很容易。

with 
  -- YourQuery: I used a stub, but you can use your actual query here, which 
  -- returns a from date and to date. If you have multiple rows, you can also
  -- output some id here, which can be used for grouping in the last step.
  YourQuery as
  ( 
    select 
      trunc(sysdate - 7) as FromDate,
      trunc(sysdate) as ToDate
    from dual),

  -- DaysBetween. This returns all the dates from the start date up to and
  -- including the end date.
  DaysBetween as
  (  
    select
      FromDate,
      FromDate + level - 1 as DayBetween,
      ToDate
    from
      YourQuery
    connect by
      FromDate + level - 1 <= ToDate)

-- As a last step, you can filter out all the days you want. 
-- This default query only filters out Saturdays and Sundays, but you
-- could add a 'not exists' check that checks against a table with known 
-- holidays.
select
  count(*)
from
  DaysBetween d
where
  trim(to_char(DAYINBETWEEN, 'DAY', 'NLS_DATE_LANGUAGE=AMERICAN'))
    not in ('SATURDAY', 'SUNDAY');