PostgreSQL实现按年、月、日、周、时、分、秒的分组统计

按年查询

select to_char(date::DATE, 'YYYY') as year,sum(shares) as shares, sum(visits) as visits 
from database_table
where date >= '2019-01-01' and  date <= '2020-01-01'  group by year order by year

PostgreSQL实现按年、月、日、周、时、分、秒的分组统计_第1张图片

按月查询

select to_char(date::DATE, 'YYYY-MM') as month,sum(shares) as shares, sum(visits) as visits 
from database_table
where date >= '2019-01-01' and  date <= '2020-01-01'  group by month order by month

PostgreSQL实现按年、月、日、周、时、分、秒的分组统计_第2张图片

按周查询

select to_char(date::DATE-(extract(dow from date::TIMESTAMP)-1||'day')::interval, 'YYYY-mm-dd') week,
sum(shares) as shares, sum(visits) as visits 
from database_table 
where date >= '2019-01-01' and  date <= '2020-01-01' group by week order by week

PostgreSQL实现按年、月、日、周、时、分、秒的分组统计_第3张图片

按天查询

select to_char(date::DATE, 'YYYY-MM-DD') as day,sum(shares) as shares, sum(visits) as visits 
from database_table
where date >= '2019-01-01' and  date <= '2020-01-01'  group by day order by day

PostgreSQL实现按年、月、日、周、时、分、秒的分组统计_第4张图片

按小时查询

select to_char(date::DATE, 'YYYY-MM-DD  HH24') as hour,sum(shares) as shares, sum(visits) as visits 
from database_table
where date >= '2019-01-01' and  date <= '2020-01-01'  group by hour order by hour

PostgreSQL实现按年、月、日、周、时、分、秒的分组统计_第5张图片

按分钟查询

select to_char(date::DATE, 'YYYY-MM-DD  HH24:MI ') as minute,sum(shares) as shares, sum(visits) as visits 
from database_table
where date >= '2019-01-01' and  date <= '2020-01-01'  group by minute order by minute

PostgreSQL实现按年、月、日、周、时、分、秒的分组统计_第6张图片

按秒查询

select to_char(date::DATE, 'YYYY-MM-DD  HH24:MI:SS ') as second,sum(shares) as shares, sum(visits) as visits 
from database_table
where date >= '2019-01-01' and  date <= '2020-01-01'  group by second order by second

PostgreSQL实现按年、月、日、周、时、分、秒的分组统计_第7张图片

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(PostgreSQL实现按年、月、日、周、时、分、秒的分组统计)