2017-06-20 128 views
0

我有一個查詢,我想返回特定列的平均值,最大值和最小值。但是,當我執行兩次或更多次時,結果彼此不同 - 這意味着每次在同一數據集上運行查詢時,我都會得到不同的平均結果。爲什麼AVG,MAX,MIN返回不同的結果?

這是爲什麼?

繼承人的代碼:

WITH avr AS (
     SELECT 
     ticker_symb, 
     day_sum, 
     cusip, 
     clos_prc, 
     nclos_prc, 
       case 
        when clos_prc is null and nclos_prc is not null 
        then (nclos_prc - LAG(nclos_prc ignore nulls) OVER (Partition by cusip ORDER BY cusip asc)) 
        when clos_prc is not null and nclos_prc is null 
        then LEAD(nclos_prc ignore nulls) OVER (Partition by cusip ORDER BY cusip asc)- LAG(naclos_prc ignore nulls) OVER (Partition by cusip ORDER BY cusip) 
        else NULL 
        end diff 
      from DAILY_SUMMARY 
      where (cusip in (select distinct cusip from thistory where 
     td between to_date('1-JAN-2017') and to_date('10-JUN-2017')))) 
      SELECT ticker_symb, 
      day_sum, 
      cusip, 
      clos_prc, 
      nclos_prc, 
      diff, 

      AVG(diff) OVER() as avr, 
      MAX(diff) OVER() as max_diff, 
      MIN(diff) OVER() as min_diff , 

      FROM avr 
      where day_sum >'1-JAN-2017' 
      ORDER BY cusip; 
+0

也許我誤解了,但他們爲什麼會一樣呢?我假設在運行查詢的時間之間新數據正在寫入'daily_summary'。 – SQLChao

+0

沒有其相同的數據集 – ana

+0

我正在執行查詢的背靠背。所以在數據集中沒有區別 – ana

回答

0

我相信你應該day_sum內訂購了,​​你正在尋找不存在的收盤價條款。按同一列進行分區和排序當然不是很典型,很可能這是導致不一致的原因。

沒有數據可以使用我已經猜到了下面的順序,但希望它足以讓您進行試驗/測試。

 
WITH avr 
AS (
SELECT 
    ticker_symb 
    , day_sum 
    , cusip 
    , clos_prc 
    , nclos_prc 
    , CASE 
    WHEN clos_prc IS NULL AND nclos_prc IS NOT NULL 
    THEN (nclos_prc 
     - LAG(nclos_prc ignore nulls) OVER (PARTITION BY cusip ORDER BY day_sum DESC) 
     ) 
    WHEN clos_prc IS NOT NULL AND nclos_prc IS NULL 
    THEN LEAD(nclos_prc ignore nulls) OVER (PARTITION BY cusip ORDER BY day_sum ASC) 
     - LAG(naclos_prc ignore nulls) OVER (PARTITION BY cusip ORDER BY day_sum DESC) 
    ELSE NULL 
    END diff 
FROM DAILY_SUMMARY 
WHERE (
    cusip IN (
    SELECT DISTINCT cusip 
    FROM thistory 
    WHERE td BETWEEN to_date('1-JAN-2017') AND to_date('10-JUN-2017') 
    ) 
    ) 
) 
select ... 
相關問題