【发布时间】: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 订购。不典型的按同一列进行分区和排序。