2017-02-21 40 views
0

我想將這種類型的數據轉換爲6天的GROUP BY格式。如何在Postgresql中分組6天

+-----+--------------+------------+ 
| gid |  cnt  | date | 
+-----+--------------+------------+ 
| 1 |  1  | 2012-02-05 | 
| 2 |  2  | 2012-02-06 | 
| 3 |  1  | 2012-02-07 | 
| 4 |  1  | 2012-02-08 | 
| 5 |  1  | 2012-02-09 | 
| 6 |  2  | 2012-02-10 | 
| 7 |  3  | 2012-02-11 | 
| 8 |  1  | 2012-02-12 | 
| 9 |  1  | 2012-02-13 | 
| 10 |  2  | 2012-02-14 | 
| 11 |  3  | 2012-02-15 | 
| 12 |  4  | 2012-02-16 | 
| 13 |  1  | 2012-02-17 | 
| 14 |  1  | 2012-02-18 | 
| 15 |  1  | 2012-02-19 | 
| 16 | NULL  | 2012-02-20 | 
| 17 |  6  | 2012-02-21 | 
| 18 | NULL  | 2012-02-22 | 
+-----+--------------+------------+ 

↓↓↓↓↓↓↓↓↓↓↓↓↓↓

enter image description here

的日期是連續的格式。

+0

真的嗎?純文本的屏幕截圖? http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557 –

+0

你能否詳細說明一下問題更多? –

+0

這不是真正的集團,因爲你有兩次考慮的記錄......就像10-02-2012。 –

回答

0

如果我理解正確的話,你需要這樣的事:

WITH x AS (SELECT date::date, (random() * 3)::int AS cnt FROM generate_series('2012-02-05'::date, '2012-02-22'::date, '1 day'::interval) AS date 
) 
SELECT start::date, 
     (start + '5 day'::interval)::date AS end, 
     sum(cnt) 
    FROM generate_series(
       (SELECT min(date) FROM x), 
       (SELECT max(date) FROM x), 
       '5 day'::interval 
     ) AS start 
    LEFT JOIN x ON (x.date >= start AND x.date <= start + '5 day'::interval) 
GROUP BY 1, 2 
ORDER BY 1 

x我效仿你的表。