使用 Postgres 对列值求和并按月对日期进行分组

eri*_*kvm 3 sql postgresql

我的 Postgres 数据库中有一个表,如下所示:

date          duration
2018-05-10      10
2018-05-12      15
2018-06-01      10
2018-06-02      20
2019-01-01      5
2019-01-02      15
2019-04-01      10
Run Code Online (Sandbox Code Playgroud)

我希望将每个月的值相加,并按年、月和月号将它们分组,如下所示:

year    month    month_number   monthly_sum
2018    May         5              25
2018    June        6              30
2019    Jan         1              20
2019    Apr         4              10
Run Code Online (Sandbox Code Playgroud)

最终得到如下所示的查询:

SELECT 
  to_char(date_trunc('month', date), 'YYYY') AS year,
  to_char(date_trunc('month', date), 'Mon') AS month,
  to_char(date_trunc('month', date), 'MM') AS month_number,
  sum(duration) AS monthly_sum
FROM timesheet 
GROUP BY year, month, month_number
Run Code Online (Sandbox Code Playgroud)

它工作得很好,我的问题是:这个查询被认为是坏的吗?如果我有大约 100k 行,它会影响性能吗?我听说使用 to_char 不如 date_trunc,这是我在这里试图避免的,我只是将 date_trunc 包装在 to_char 中。另外,一个子句中有三个值GROUP BY,会产生什么影响吗?

Gor*_*off 5

查询还不错,但是你可以简化它。

SELECT to_char(date_trunc('month', date), 'YYYY') AS year,
       to_char(date_trunc('month', date), 'Mon') AS month,
       to_char(date_trunc('month', date), 'MM') AS month_number,
       sum(duration) AS monthly_sum
FROM timesheet 
GROUP BY date_trunc('month', date);
Run Code Online (Sandbox Code Playgroud)

从性能角度来看,较短的GROUP BY键对性能的影响很小,但这不是我担心的事情。