2017-06-16 91 views
0

我想查詢一個表以找出Postgres中由日期,日期和月份創建的對象的計數。Postgres按日期與時區計算

取數最近30天

SELECT d.date, count(se.id) 
FROM (SELECT to_char(date_trunc('day', (current_date - offs)), 'YYYY-MM-DD') AS date 
FROM generate_series(0, 30) AS offs) d LEFT OUTER JOIN 
    someTable se 
    ON d.date = to_char(date_trunc('day', se.created_at), 'YYYY-MM-DD') 
GROUP BY d.date; 

取一天算

select to_char(created_at,'day') as Day, 
     extract(month from created_at) as Date, 
     count("id") as "Count" 
from someTable 
group by 1,2 

按月讀取計數

select to_char(created_at,'Mon') as mon, 
     extract(year from created_at) as yyyy, 
     count("id") as "Count" 
from someTable 
group by 1,2 

這對我來說很好。我的問題是,我想根據不同的時區提取數據。我已將時間存儲在UTC中。我將能夠在不同的時區運行這些查詢。

這樣做的最佳方法是什麼?

回答

1

檢查此answer以獲得不同時區Postgres中的日期時間。

取數最近30天

SELECT d.date, count(se.id) 
FROM (SELECT to_char(date_trunc('day', (current_date - offs)), 'YYYY-MM-DD') AS date 
FROM generate_series(0, 30) AS offs) d LEFT OUTER JOIN 
    someTable se 
    ON d.date = to_char(date_trunc('day', se.created_at::timestamp with time zone at time zone 'EST'), 'YYYY-MM-DD') 
GROUP BY d.date; 

取一天算

select to_char(created_at::timestamp with time zone at time zone 'EST','day') as Day, 
     extract(month from created_at) as Date, 
     count("id") as "Count" 
from someTable 
group by 1,2 

按月讀取計數

select to_char(created_at::timestamp with time zone at time zone 'EST','Mon') as mon, 
     extract(year from created_at) as yyyy, 
     count("id") as "Count" 
from someTable 
group by 1,2 

另請參閱此Postgres documentation瞭解有關datetime的時區。