我有一些
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
我想创建间隔为 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
表中的日期在期间条件内加入,并按 merchant_id
和期间分组(periods.date
是开始期间日期就足够了).最后,我们获取所需的一切:开始日期、结束日期、商家和金额。
关于PostgreSQL - 聚合系列间隔 2 年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33467223/