2016-09-22 33 views
0

我有一個查詢,我算的行數每年學年:集團在Postgres的

SELECT 
    count(*) as activation_count 
, extract(year from activated_at) as year 
FROM "activations" 
WHERE ... 
GROUP BY year 

,但我想,而不是有多年爲從九月到九月,而不是1至1月。因此按學校年代而不是日曆年進行分組。

我可以修改我的查詢嗎?

而且更普遍,是可以按時間範圍,並指定偏移到它,比如:extract(year from activated_at offset interval 2 month) as year(這是行不通的,只是我想要什麼的想法)

回答

1

假設某人其activated_at '2016-09-01'應該計爲year = 2017,您可以在extract(從9月到1月的數學意義上的翻譯)中添加4個月至activated_at

SELECT * FROM activations ; 
┌────────────────────────┐ 
│  activated_at  │ 
├────────────────────────┤ 
│ 2016-08-01 00:00:00+02 │ 
│ 2016-09-01 00:00:00+02 │ 
│ 2016-10-01 00:00:00+02 │ 
│ 2017-02-02 00:00:00+01 │ 
└────────────────────────┘ 
(4 rows) 


SELECT COUNT(*), 
     EXTRACT(year FROM (activated_at + '4 months'::interval)) AS year 
FROM activations 
GROUP BY year; 
┌───────┬──────┐ 
│ count │ year │ 
├───────┼──────┤ 
│  3 │ 2017 │ 
│  1 │ 2016 │ 
└───────┴──────┘ 
(2 rows) 

如果應該算作year = 2016你可以刪除8個月代替。

1

你基本上要的是九月爲「明年」後對待所有日期,所以下面應該工作:

select count(*) as activation_count, 
     case 
      when extract(month from activated_at) >= 9 then extract(year from activated_at) + 1 
      else extract(year from activated_at) 
     end as school_year 
from activations 
group by school_year;