在Teradata中计算营业日

时间:2017-03-26 23:15:42

标签: sql teradata

我需要在工作日计算方面提供帮助。

我有两张桌子

1)一个表ACTUAL_TABLE包含订单日期和具有timestamp数据类型的联系日期。 2)第二个表BUSINESS_DATES列出了每个日历日期,并有一个标记表示周末日。

使用这两个表,我需要确保在这两个字段之间计算工作日而不是日历天(这是当前逻辑)。

我的思维过程是首先通过将ORDER_DATETABLE_DATE字段进行比较来获取一系列日期,然后对CONTACT_DATETABLE_DATE字段进行类似的比较。这样我就可以从BUSINESS_DATES表中获取一个范围,我可以用它来计算天数,sum(Holiday_WKND_Flag)字段使结果看起来像:

Order#   | Count(*) As DAYS | SUM(WEEKEND DATES)
100      | 25               | 8

然而,这只适用于我使用特定订单号并且无法将所有订单号带入子查询的情况。

我的查询:

SELECT SUM(Holiday_WKND_Flag), COUNT(*) FROM
(
SELECT 
* FROM 
BUSINESS_DATES
WHERE BUSINESS.Business  BETWEEN (SELECT ORDER_DATE FROM ACTUAL_TABLE
WHERE ORDER#  = '100'
)

AND

(SELECT CONTACT_DATE FROM ACTUAL_TABLE
WHERE ORDER# = '100'
)

TEMP

上传表格结构供您参考。

enter image description here

3 个答案:

答案 0 :(得分:0)

SELECT      ORDER#, SUM(Holiday_WKND_Flag), COUNT(*) 
FROM        business_dates  bd
INNER JOIN  actual_table    at ON bd.table_date BETWEEN at.order_date AND at.contact_date
GROUP BY    ORDER#

答案 1 :(得分:0)

您最好在每个日期分配一个商务日数,而不是加入BETWEEN(总是导致错误的商品加入),然后再加上COUNT,最好只计算一次作为列添加到您的日历表中)。然后它是两个Equi-Joins并且不需要聚合:

WITH cte AS
 (
   SELECT
      Cast(table_date AS DATE) AS table_date, 
      -- assign a consecutive number to each busines day, i.e. not increased during weekends, etc.
      Sum(CASE WHEN Holiday_WKND_Flag = 1 THEN 0 ELSE 1 end)
      Over (ORDER BY table_date
            ROWS Unbounded Preceding) AS business_day_nbr
   FROM business_dates
 )
SELECT ORDER#, 
   Cast(t.contact_date AS DATE) - Cast(t.order_date AS DATE) AS #_of_days
   b2.business_day_nbr - b1.business_day_nbr AS #_of_business_days
FROM actual_table AS t
JOIN cte AS b1
  ON Cast(t.order_date AS DATE) = b1.table_date
JOIN cte AS b2
  ON Cast(t.contact_date AS DATE) = b2.table_date

顺便问一下,为什么table_dateorder_date timestamp而不是date? 从Oracle移植?

答案 2 :(得分:0)

您可以使用此查询。希望它有所帮助

select order#, 
    order_date, 
    contact_date, 
    (select count(1) 
            from business_dates_table 
            where table_date between a.order_date and a.contact_date 
                  and holiday_wknd_flag = 0
    ) business_days 
from actual_table a