2015-11-01 54 views
1

我有一些PostgreSQL的 - 骨料序列區間2年

 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(日期)::日期,當前(日期)::日,「2年)

我想表這樣的:

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

但有一些我的查詢中出現錯誤,因爲所有系列的總和(銷售)是相同的,並且總和是錯誤的。事件如果我總結出售約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; 

請尋求幫助。

+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是足夠的開始期限日期)。最後,我們把我們需要的一切:開始日期,結束日期,商家和總和。