【发布时间】:2014-07-31 13:52:03
【问题描述】:
下面的查询将来自first 的结果分组到4 个等距的日期箱中,并在每个箱中聚合the_value 的平均值。
WITH first as(
SELECT
extract(EPOCH FROM foo.t_date) as the_date,
foo_val as the_value
FROM bar
INNER JOIN foo
ON
foo.user_id = bar.x_id
and
foo.user_name = 'xxxx'
)
SELECT bin, round(sum(bin_sum) OVER w /sum(bin_ct) OVER w, 2) AS running_avg
FROM (
SELECT width_bucket(first.the_date
, x.min_epoch, x.max_epoch, x.bins) AS bin
, sum(first.the_value) AS bin_sum
, count(*) AS bin_ct
FROM first
, (SELECT MIN(first.the_date) AS min_epoch
, MAX(first.the_date) AS max_epoch
, 4 AS bins
FROM first
) x
GROUP BY 1
) sub
WINDOW w AS (ORDER BY bin)
ORDER BY 1;
我希望能够只计算每个 bin 中最低的 20 个 the_value 的平均值。从 Stackoverflow 上的其他帖子中,我看到这是可能的,也许 ORDER BY the_value 和 rank() 是最好的方法。但我的困难是我不确定我当前的查询应该在哪里修改以实现这一点。
任何见解都将不胜感激。
Postgres 9.3 版
【问题讨论】:
-
任何见解将不胜感激可用数据将不胜感激。
-
以及您的 Postgres 版本 (always)。
-
@ErwinBrandstetter - 以上查询中作用于
first的部分取自您提交给link 的答案。 -
@user3204587:我觉得它看起来很眼熟。 ;)
标签: sql postgresql aggregate-functions window-functions sql-limit