Daily average for the month (needs number of days in month)

回眸只為那壹抹淺笑 提交于 2019-12-06 02:22:52

A bit shorter and faster and you get the number of days instead of an interval:

SELECT EXTRACT(day FROM date_trunc('month', now()) + interval '1 month'
                                                   - interval '1 day')

It's possible to combine multiple units in a single interval value . So we can use '1 mon - 1 day':

SELECT EXTRACT(day FROM date_trunc('month', now()) + interval '1 mon - 1 day')

(mon, month or months work all the same for month units.)

To divide the daily sum by the number of days in the current month (orig. question):

SELECT t::date AS the_date
     , SUM(c)  AS c
     , SUM(c) / EXTRACT(day FROM date_trunc('month', t::date)
                               + interval '1 mon - 1 day') AS a
FROM   dycounts
GROUP  BY 1;

To divide monthly sum by the number of days in the current month (updated question):

SELECT DATE_TRUNC('month', t)::date AS t
      ,SUM(c) AS c
      ,SUM(c) / EXTRACT(day FROM date_trunc('month', t)::date
                               + interval '1 mon - 1 day') AS a
FROM   dycounts
GROUP  BY 1;

You have to repeat the GROUP BY expression if you want to use a single query level.

Or use a subquery:

SELECT *, c / EXTRACT(day FROM t + interval '1 mon - 1 day') AS a
FROM  (
   SELECT date_trunc('month', t)::date AS t, SUM(c) AS c
   FROM   dycounts
   GROUP  BY 1
   ) sub;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!