使用Oracle SQL查找偏离平均天数的最佳方法

时间:2014-07-11 16:51:40

标签: sql oracle

有没有更好的方法让我发现每行偏离平均延迟的天数?

这是我对数据的查询:

COL ORD_ID FORMAT A6
COL TOTAL FORMAT '$9,999,999.99'
COL DELAY FORMAT A5
SELECT ID AS "ORD_ID", CUSTOMER_ID, TOTAL, 
(DATE_SHIPPED - DATE_ORDERED) AS "DELAY",
  (SELECT ROUND(AVG(DATE_SHIPPED - DATE_ORDERED))
  FROM S_ORD) AS "AVG_DELAY", 
ROUND((DATE_SHIPPED - DATE_ORDERED) - 
  (SELECT AVG(DATE_SHIPPED - DATE_ORDERED)
  FROM S_ORD)) AS "DEVIATION"
FROM S_ORD
WHERE (DATE_SHIPPED - DATE_ORDERED) > 
  (SELECT AVG((DATE_SHIPPED - DATE_ORDERED))
  FROM S_ORD)
  GROUP BY ID, CUSTOMER_ID, (DATE_SHIPPED - DATE_ORDERED), TOTAL
ORDER BY TOTAL DESC
ORD_ID CUSTOMER_ID          TOTAL DELAY  AVG_DELAY  DEVIATION
------ ----------- -------------- ----- ---------- ----------
   109         213  $1,020,935.00    20         13          7 
   107         211    $142,171.00    14         13          1 
    97         201     $84,000.00    20         13          7 
   104         208     $32,430.00    20         13          7 
   101         205      $8,056.60    15         13          2 
    99         203      $7,707.00    18         13          5 
   105         209      $2,722.24    14         13          1 
   103         208        $377.00    20         13          7 

 8 rows selected 

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

使用窗口函数(在Oracle中称为“分析函数”)可以避免嵌套的子选择

SELECT *
FROM (
  SELECT id AS ord_id,
         customer_id,
         total,
         (date_shipped - date_ordered) AS delay,
         avg(date_shipped - date_ordered) OVER () AS avg_delay,
         (date_shipped - date_ordered) - avg(date_shipped - date_ordered) OVER () AS deviation
  FROM s_ord
) t
WHERE delay > avg_delay
ORDER BY total DESC

这可能也比你的版本更快。