使用Count运行子查询时出现Teradata假脱机空间问题

时间:2016-12-22 08:54:08

标签: sql subquery query-optimization teradata

我使用以下查询来计算所有订单号的两个日期之间的营业日。工作日已在teradata表Common_WorkingCalendar中提供。但是,当我执行查询时,我也面临着假脱机空间问题。我的数据实验室里有足够的空间。需要优化查询。感谢任何投入。

SELECT 
tx."OrderNumber",
(SELECT COUNT(1) FROM Common_WorkingCalendar
WHERE CalDate between Cast(tx."TimeStamp" as date) and Cast(mf.ShipDate as  date)) as BusDays
from StoreFulfillment ff
inner join StoreTransmission tx 
            on tx.OrderNumber = ff.OrderNumber
        inner join StoreMerchandiseFulfillment mf 
            on mf.OrderNumber = ff.OrderNumber

1 个答案:

答案 0 :(得分:2)

这是一种非常低效的方法来获得此计数,从而导致产品加入。

建议的方法是在日历中添加一个序号,该序号仅在工作日增加(使用SUM(CASE WHEN businessDay THEN 1 ELSE 0 END) OVER (ORDER BY CalDate ROWS UNBOUNDED PRECEDING)计算),然后是两个联接,包括开始日期和结束日期。

如果需要进行大量计算,最好添加一个新列,否则可以动态执行:

WITH cte AS 
 (
  SELECT CalDate,
     -- as this table only contains business days you can use this instead
     row_number(*) Over (ORDER BY CalDate) AS DayNo
  FROM Common_WorkingCalendar
 )
SELECT
  tx."OrderNumber",
  to_dt.DayNo - from_dt.DayNo AS BusDays
FROM StoreFulfillment ff
INNER JOIN StoreTransmission tx 
            ON tx.OrderNumber = ff.OrderNumber
        INNER JOIN StoreMerchandiseFulfillment mf 
            ON mf.OrderNumber = ff.OrderNumber
JOIN cte AS from_dt
  ON from_dt.CalDate = Cast(tx."TimeStamp" AS DATE)
JOIN cte AS to_dt
  ON to_dt.CalDate = Cast(mf.ShipDate AS  DATE)