PostgreSQL - 聚合系列间隔 2 年

PostgreSQL - aggregate series interval 2 years

我有一些

        id_merchant    |    data    |  sell
                    11 | 2009-07-20 | 1100.00
                    22 | 2009-07-27 | 1100.00
                    11 | 2005-07-27 |  620.00
                    31 | 2009-08-07 | 2403.20
                    33 | 2009-08-12 | 4822.00
                    52 | 2009-08-14 | 4066.00
                    52 | 2009-08-15 |  295.00
                    82 | 2009-08-15 |    0.00
                    23 | 2011-06-11 |  340.00
                    23 | 2012-03-22 | 1000.00
                    23 | 2012-04-08 | 1000.00
                    23 | 2012-07-13 |   36.00
                    23 | 2013-07-17 | 2480.00
                    23 | 2014-04-09 | 1000.00
                    23 | 2014-06-10 | 1500.00
                    23 | 2014-07-20 |  700.50

我想将 table 创建为 select,间隔为 2 年。商家的第一个日期是 min(date)。所以我生成系列 (min(date)::date,current(date)::date,'2 years')

我想达到 table 那样:

        id_merchant |   data          |  sum(sell)
                 23 | 2011-06-11      |  12382.71
                 23 | 2013-06-11      |  12382.71
                 23 | 2015-06-11      |  12382.71

但是我的查询有一些错误,因为 sum(sell) 对于所有系列都是相同的,而且总和是错误的。事件如果我总销售额是 6000 而不是 12382.71。

我的查询:

select m.id_gos_pla,
       generate_series(m.min::date,dath()::date,'2 years')::date,
       sum(rch.suma)
from   rch, minmax m
where  rch.id_gos_pla=m.id_gos_pla
group by m.id_gos_pla,m.min,m.max
order by 1,2;

求助。

我会这样做:

select
        periods.id_merchant,
        periods.date as period_start,
        (periods.date + interval '2' year - interval '1' day)::date as period_end,
        coalesce(sum(merchants.amount), 0) as sum
    from
    (
        select
                id_merchant,
                generate_series(min(date), max(date), '2 year'::interval)::date as date
            from merchants
                group by id_merchant
    ) periods
    left join merchants on
            periods.id_merchant = merchants.id_merchant and
            merchants.date >= periods.date and
            merchants.date < periods.date + interval '2' year
        group by periods.id_merchant, periods.date
        order by periods.id_merchant, periods.date

我们使用子查询根据该商户的第一个日期和所需的时间间隔为每个 id_merchant 生成日期段。然后在期间条件内的日期与 merchants table 加入它,并按 merchant_id 和期间分组(periods.date 是足够的开始期间日期)。最后我们获取所需的一切:开始日期、结束日期、商家和金额。