【问题标题】:Moving average on other window function redshift其他窗口函数红移的移动平均
【发布时间】:2022-09-24 12:05:58
【问题描述】:

我遇到了一个问题,需要帮助

我有一张这样的桌子:

created_time_id | txn_src 
1-1-2017     | A
1-1-2017     | A
1-1-2017     | B
1-1-2017     | A
1-1-2017     | C
2-1-2017     | A
2-1-2017     | C
2-1-2017     | B
2-1-2017     | A
3-1-2017     | A
3-1-2017     | A
3-1-2017     | C

在红移中,我必须为上表创建一个移动平均列以及按日期划分的源计数分区

目前我已经写了以下查询

select
    txn_src,
    created_time_id::char(8)::date as \"time\",
    count_payment
from
    (
    select
        txn_src,
        created_time_id,
        count(1) as count_payment,
        row_number() over (partition by created_time_id
    order by
        count(1) desc) as seqnum
    from
        my_table
    where
        created_time_id >= \'1-1-2017\' and txn_source is not null 
    group by
        1,
        2
     ) x
where
    seqnum <= 10
order by
    \"time\" ,
    count_payment desc

这给了我正确的输出,比如

1-1-2017 | A | 3
1-1-2017 | B | 1

等等

我需要这样的移动平均线

time     |src|cnt|mvng_avg
1-1-2017 | A | 3 |3
1-1-2017 | B | 1 |1
1-1-2017 | C | 1 |1
2-1-2017 | A | 2 |2.5

等等 .. 任何人都可以为此提出一些好的解决方案。

  • 你能分享你原来的输入表吗?
  • Redshift 还是 Postgres?这是两个非常不同的 DBMS 产品。
  • 我正在使用红移。我将无法共享输入表,但它们或多或少是这样的。

标签: sql amazon-web-services amazon-redshift window-functions


【解决方案1】:

经过一番努力,我能够使用以下查询解决此问题

with txn_source_by_date as (
select
        txn_source ,
        created_time_id,
        count(1) as count_payment, 
        row_number() over (partition by created_time_id
order by
        count(1) desc) as seqnum
from
        my_table
where
        created_time_id >= 20220801
    and txn_source is not null
group by
        1,
        2
)
select
    txn_source,
    created_time_id::char(8)::date as "time",
    count_payment,
    avg(count_payment) over (partition by txn_source  
order by
    created_time_id rows between 29 preceding and current row ) mvng_avg
from
    txn_source_by_date
group by
    txn_source,
    created_time_id,
    count_payment
order by
    "time",
    txn_source 

【讨论】:

    猜你喜欢
    • 2020-12-28
    • 2019-03-22
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2020-07-12
    • 2022-01-26
    相关资源
    最近更新 更多