我如何在PostgreSQL中的两个日期之间获取按月的记录(按日期将其月份分组)?

时间:2018-11-02 07:24:08

标签: postgresql

  

我正在使用以下查询明智地获取记录月份,但它给   错误数据

SELECT 
     (count( server_time::timestamp::date)) , 
     min(server_time::timestamp::date) as "Month Date"
FROM 
     complaint_details_v2 
WHERE 
     server_time between '2018/08/01' and '2018/10/30' 
GROUP BY 
     floor((server_time::timestamp::date  - '2018/08/01'::date)/30)
ORDER BY 
     2 ASC

结果

Count Month Date
2774  2018-08-01
5893  2018-08-31
1193  2018-09-30

但是结果将会是

Count Month Date
2774  2018-08-01
5893  2018-09-01
1193  2018-10-01

1 个答案:

答案 0 :(得分:0)

使用date_trunc

demo:db<>fiddle

SELECT
    count(*), 
    date_trunc('month', servertime)::date as month_date
FROM log
GROUP BY date_trunc('month', servertime)
ORDER BY 2