How to group by week in postgresql

后端 未结 2 1660
夕颜
夕颜 2021-02-02 06:04

I\'ve a database table commits with the following columns:

id | author_name | author_email | author_date (timestamp) | total_lines

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-02 06:53

    If you have multiple years, you should take the year into account as well. One way is:

    SELECT date_part('year', author_date::date) as year,
           date_part('week', author_date::date) AS weekly,
           COUNT(author_email)           
    FROM commits
    GROUP BY year, weekly
    ORDER BY year, weekly;
    

    A more natural way to write this uses date_trunc():

    SELECT date_trunc('week', author_date::date) AS weekly,
           COUNT(author_email)           
    FROM commits
    GROUP BY weekly
    ORDER BY weekly;
    

提交回复
热议问题