2017-02-23 74 views
1

我有問題試圖圍繞如何從我的Postgres數據庫中提取一些時間序列統計信息。Postgresql每個記錄的時間序列

例如,我有幾家商店。我記錄每個店有多少銷量,看起來像一個表中的每一天進行:

+------------+----------+-------+ 
| Date | Store ID | Count | 
+------------+----------+-------+ 
| 2017-02-01 |  1 | 10 | 
| 2017-02-01 |  2 | 20 | 
| 2017-02-03 |  1 | 11 | 
| 2017-02-03 |  2 | 21 | 
| 2017-02-04 |  3 | 30 | 
+------------+----------+-------+ 

我想對每個商店不同的線和空白日期酒吧/線圖已填充顯示此數據0.

我已經成功地使用generate_series來顯示每天的總和(將所有商店合併爲一個總和),但我無法弄清楚如何分開它,因此每個商店都有一個值一天...結果是這樣的:

["Store ID 1", 10, 0, 11, 0] 
["Store ID 2", 20, 0, 21, 0] 
["Store ID 3", 0, 0, 0, 30] 

回答

2

有必要建立一個交叉聯接日期X專賣店:

select store_id, array_agg(total order by date) as total 
from (
    select store_id, date, coalesce(sum(total), 0) as total 
    from 
     t 
     right join (
      generate_series(
       (select min(date) from t), 
       (select max(date) from t), 
       '1 day' 
      ) gs (date) 
      cross join 
      (select distinct store_id from t) s 
     ) using (date, store_id) 
    group by 1,2 
) s 
group by 1 
order by 1 
; 
store_id | total  
----------+------------- 
     1 | {10,0,11,0} 
     2 | {20,0,21,0} 
     3 | {0,0,0,30} 

的樣本數據:

create table t (date date, store_id int, total int); 
insert into t (date, store_id, total) values 
('2017-02-01',1,10), 
('2017-02-01',2,20), 
('2017-02-03',1,11), 
('2017-02-03',2,21), 
('2017-02-04',3,30); 
+0

你是個英雄。這很好,謝謝! –