Postgres,每天计数条目

时间:2018-03-20 08:03:07

标签: postgresql time-series grafana

我有一个包含几个字段的表格,但我只想计算state字段所在的每日条目数。 '被拒绝'。字段createdAt是带有时区的时间戳。

id | createdAt                  | state
------------------------------------------
1  | 2018-01-17 13:53:17.303+00 | rejected
2  | 2017-10-19 20:39:18.232+00 | approved

所以我想计算两个时间戳之间每天的行数。没有任何条目的天数应返回0或NULL。 我创建的查询返回正确的时间序列,但不知何故,我的连接或计数似乎是奇怪的。它返回了数千个条目,但通常只有0到20之间。(整个表少于3800个条目)

SELECT serie.day AS time, count(t."createdAt") AS created
FROM (
   SELECT generate_series(
       to_timestamp(1518248353)::date,
       to_timestamp(1521469246)::date, 
       interval '1 day'
   ) AS day
   FROM users t
) serie
LEFT JOIN users t ON t."createdAt"::date = serie.day::date 
     WHERE state ILIKE 'rejected'
GROUP  BY serie.day
ORDER  BY time;

错误的结果:

2018-02-10 00:00:00+00  11619
2018-02-11 00:00:00+00  23238
2018-02-12 00:00:00+00  27111
2018-02-13 00:00:00+00  19365
2018-02-14 00:00:00+00  15492
2018-02-15 00:00:00+00  34857
2018-02-16 00:00:00+00  34857
2018-02-17 00:00:00+00  15492
2018-02-18 00:00:00+00  46476
2018-02-19 00:00:00+00  15492
2018-02-21 00:00:00+00  27111
2018-02-22 00:00:00+00  19365
2018-02-23 00:00:00+00  11619
2018-02-24 00:00:00+00  3873
2018-02-25 00:00:00+00  3873
...

预期结果如下:

2018-02-10 00:00:00+00  3
2018-02-11 00:00:00+00  9
2018-02-12 00:00:00+00  0
2018-02-13 00:00:00+00  19
2018-02-14 00:00:00+00  15
2018-02-15 00:00:00+00  3
2018-02-16 00:00:00+00  7
...

1 个答案:

答案 0 :(得分:1)

为什么要将生成的系列加入子查询中的用户表?我认为这是你的问题。通常,当您使用generate_series()时,您只需提供开始日期时间,结束日期时间和间隔,然后将该系列生成为表格。

请改为尝试:

SELECT
    serie.day AS time,
    COUNT(t."createdAt") AS created
FROM (
    SELECT date_series::date AS day
    FROM generate_series(
        to_timestamp(1518248353)::date,
        to_timestamp(1521469246)::date,
        '1 day'
    ) AS date_series
) AS serie
LEFT JOIN users t ON t."createdAt"::date = serie.day::date 
    AND state ILIKE 'rejected'
GROUP  BY serie.day
ORDER  BY time;