【发布时间】:2019-02-21 18:42:57
【问题描述】:
我的 Postgres DB 中有一个表,看起来像这样:
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
我希望将每个月的值相加,并按年、月和月数将它们分组为如下所示:
year month month_number monthly_sum
2018 May 5 25
2018 June 6 30
2019 Jan 1 20
2019 Apr 4 10
最后得到如下查询:
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
它工作得很好,我的问题是:这个查询被认为是坏的吗?如果我喜欢.. 100k 行,它会影响性能吗?我听说使用 to_char 不如 date_trunc,这是我在这里试图避免的,我只是将 date_trunc 包裹在一个 to_char 中。
另外,GROUP BY 子句中包含三个值,它会影响什么吗?
【问题讨论】:
-
你可以用extract代替to_char
标签: sql postgresql