3

我有一张如下表:

CREATE TABLE counts
(
    T TIMESTAMP NOT NULL,
    C INTEGER NOT NULL
);

我从中创建了以下视图:

CREATE VIEW micounts AS 
SELECT DATE_TRUNC('minute',t) AS t,SUM(c) AS c FROM counts GROUP BY 1;

CREATE VIEW hrcounts AS
SELECT DATE_TRUNC('hour',t) AS t,SUM(c) AS c,SUM(c)/60 AS a
FROM micounts GROUP BY 1;

CREATE VIEW dycounts AS
SELECT DATE_TRUNC('day',t) AS t,SUM(c) AS c,SUM(c)/24 AS a
FROM hrcounts GROUP BY 1;

现在问题来了,当我想创建每月计数以知道将每日总和除以得到平均列 a 时,即特定月份的天数。

我知道要在 PostgreSQL 中度过你可以做的事:

SELECT DATE_PART('days',DATE_TRUNC('month',now())+'1 MONTH'::INTERVAL-DATE_TRUNC('month',now()))

但我不能使用now(),我必须以某种方式让它知道分组完成时的月份。任何建议,即应该替换什么???在这个视图中:

CREATE VIEW mocounts AS
SELECT DATE_TRUNC('month',t) AS t,SUM(c) AS c,SUM(c)/(???) AS a
FROM dycounts
GROUP BY 1;
4

1 回答 1

1

更短更快一点,你会得到天数而不是interval

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

可以将多个单位组合成一个interval值。所以我们可以使用'1 mon - 1 day'

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

( monmonth或者months对于月份单位都一样。)

每日总和除以当月的天数(原始问题):

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;

每月总和除以当月的天数(更新问题):

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;

GROUP BY如果要使用单个查询级别,则必须重复该表达式。

或使用子查询

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;
于 2013-10-08T07:32:09.647 回答