2017-06-16 90 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的时区。