【问题标题】:Why do AVG, MAX, MIN return different results?为什么 AVG、MAX、MIN 返回不同的结果?
【发布时间】:2017-06-20 19:49:30
【问题描述】:

我有一个查询,我想在其中返回特定列的平均值、最大值和最小值。但是,当我执行两次或更多次时,结果彼此不同——这意味着每次我在同一个数据集上运行查询时,我都会得到不同的平均结果。

为什么会这样?

代码如下:

   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;

【问题讨论】:

  • 也许我理解错了,但为什么它们会是一样的呢?我假设在您运行查询之间有新数据被写入daily_summary
  • 不是同一个数据集
  • 我正在背靠背运行查询。所以数据集没有区别
  • cusip 是唯一的吗?您在您的分区条款中对此进行订购。如果它不是唯一的,那么您的 partition by 语句是不确定的,这意味着您每次运行时可能会得到不同的顺序。尝试在 order by 语句中添加第二列以确保唯一性,因此每次都将返回相同的顺序。
  • 我认为您应该在您正在寻找收盘价的 over 条款中按 day_sum 订购。不典型的按同一列进行分区和排序。

标签: sql oracle


【解决方案1】:

我认为您应该在您正在寻找没有收盘价的 over 条款中按 day_sum 订购。按同一列进行分区和排序当然不是典型的,这很可能是导致不一致的原因。

在没有数据的情况下,我猜到了下面看到的顺序,但希望它足以让您试用/测试。

带avr 作为 ( 选择 ticker_symb , 日总和 , 尖头 , 关闭_prc , nclos_prc , 案子 当 clos_prc 为空且 nclos_prc 不为空时 那么(nclos_prc - LAG(nclos_prc 忽略空值) OVER (PARTITION BY cusip ORDER BY day_sum DESC ) ) 当 clos_prc 不为 NULL 且 nclos_prc 为 NULL 时 THEN LEAD(nclos_prc ignore nulls) OVER (PARTITION BY cusip ORDER BY day_sum ASC ) - LAG(naclos_prc 忽略空值) OVER (PARTITION BY cusip ORDER BY day_sum DESC ) 否则为空 结束差异 来自 DAILY_SUMMARY 在哪里 ( 尖点输入( 选择不同的尖点 来自历史 td 在 to_date('1-JAN-2017') 和 to_date('10-JUN-2017') 之间的位置 ) ) ) 选择 ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 2012-08-26
    • 1970-01-01
    • 2019-04-10
    • 2013-01-05
    • 2022-12-13
    • 2012-07-28
    相关资源
    最近更新 更多