2017-06-17 51 views
0

這是一個基於前一個問題一個subquestion:集團通過isoweek - PostgreSQL的

Split values from an interval and group by isoweek - Postgresql

的問題是如何分組這個由isoweek

CREATE TABLE task 
    (id int4, start date, stop date, hr int4);  
INSERT INTO task 
    (id, start, stop, hr) 
VALUES 
    (1, '2017-01-01','2017-01-31', 80), 
    (2, '2017-01-01','2017-02-28', 120); 

基於帕特里克答案我發現這解決方案:

SELECT id,to_char(iso, 'iyyy-iw'),(hr/weeks)::numeric (5,2) as hr_week 
FROM (SELECT id,hr,generate_series(start,stop,interval '1 week') as iso, 
(stop - start)/7 as weeks FROM task) as sub 

http://sqlfiddle.com/#!15/93ee1/78

下一個步驟是「組羣」是這樣的:

2016-52 35 
2017-01 35 
2017-02 35 
2017-03 35 
2017-04 35 
2017-05 15 
2017-06 15 
2017-07 15 
2017-08 15 

我無法弄清楚如何做到這一點。任何幫助讚賞。

TIA,

回答

1

SQL Fiddle

的PostgreSQL 9.3架構設置

CREATE TABLE task 
    (id int4, start date, stop date, hr int4);  
INSERT INTO task 
    (id, start, stop, hr) 
VALUES 
    (1, '2017-01-01','2017-01-31', 80), 
    (2, '2017-01-01','2017-02-28', 120); 

查詢1

SELECT 
    to_char(iso, 'iyyy-iw') as YYY_WK 
    , max(weeks) as weeks 
    , sum((hr/weeks)::numeric (5,2)) as hr_week 
FROM (
    SELECT 
     id 
    , hr 
    , generate_series(start,stop,interval '1 week') as iso 
    , (stop - start)/7 as weeks 
    FROM task 
    ) as sub 
group by 
    to_char(iso, 'iyyy-iw') 

Results

| yyy_wk | weeks | hr_week | 
|---------|-------|---------| 
| 2017-08 |  8 |  15 | 
| 2017-06 |  8 |  15 | 
| 2017-02 |  8 |  35 | 
| 2017-03 |  8 |  35 | 
| 2017-07 |  8 |  15 | 
| 2016-52 |  8 |  35 | 
| 2017-05 |  8 |  15 | 
| 2017-01 |  8 |  35 | 
| 2017-04 |  8 |  35 | 
+0

我希望這將涵蓋空周爲好。謝謝! – sibert

0

同時,我發現了另一個解決方案,基於CTE。然而,這不包括空的周,但也是一個解決方案。我會認爲@已被用作更可靠的答案。

WITH list as (
SELECT id,to_char(iso, 'iyyy-iw'),(hr/weeks)::numeric (5,2) as hr_week 
FROM (SELECT id,hr,generate_series(start,stop,interval '1 week') as iso, 
(stop - start)/7 as weeks FROM task) as sub) 

SELECT DISTINCT ON (week) week, sum(hr_week) 
FROM list 
GROUP BY 1 

http://sqlfiddle.com/#!15/93ee1/113