2017-03-26 90 views
0

我需要工作日計算方面的幫助。計算Teradata中的營業日

我有兩個表

1)一個表ACTUAL_TABLE含有訂單日期和接觸時間與時間戳的數據類型。 2)第二個表BUSINESS_DATES列出了每個日曆日期並且有一個標誌來表示週末日。

使用這兩個表格,我需要確保工作日而不是日曆日(這是當前的邏輯)在這兩個字段之間進行計算。

我的思維過程是通過TABLE_DATE場比較ORDER_DATE首先得到一定範圍的日期,然後做的CONTACT_DATE類似的比較,以TABLE_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

回答

0

相反之間的連接上(這總是導致一個不好的產品加入),接着是算你更好bussines天數分配給每個日期(在最好的情況下,這是隻計算一次並作爲列添加到您的日曆表中)。然後,它的兩位同等聯接,無聚集需要:

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_datetimestamp代替date? 從Oracle移植?

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