PostgreSQL - 聚合系列间隔2年

时间:2015-11-01 21:07:23

标签: postgresql date sum aggregate series

我有一些

        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

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

我想这样表:

        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;

请求帮助。

1 个答案:

答案 0 :(得分:1)

我会这样做:

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表与日期相结合,并按merchant_id分组,期间(periods.date是足够的起始期限日期)。最后我们采取我们需要的一切:开始日期,结束日期,商家和总和。