2017-06-20 16 views
0

特定の列の平均値、最大値、最小値を返したいクエリがあります。しかし、私が2回以上実行すると、結果はお互いに異なります。つまり、同じデータセットでクエリを実行するたびに、平均結果が異なります。なぜ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 ... 
関連する問題