小编chr*_*g89的帖子

随着时间的推移Postgres累积计数

我正在尝试查找一个时间表中一个月内的活动订阅数。

表格:订阅字段:

  • ID
  • “创立日期”
  • “ deletionDate”

在以下情况下,订阅被视为在特定时间戳下处于活动状态:

  1. deleteDate为null
  2. 特定的时间戳介于creationDate和deleteDate之间

例:

  • 订阅A具有creationDate“ 2014-06-27 11:37:34.205 + 00”和deleteDate“ 2014-08-01 04:16:34.435 + 00”。订阅A被认为在2014年6月,2014年7月和2014年8月处于活动状态。
  • 订阅B的创建日期为“ 2014-06-27 11:37:34.205 + 00”,而删除日期为“ 2014-06-28 11:37:34.205 + 00”。订阅B仅在2014年6月有效。
  • 订阅C的creationDate为“ 2014-06-27 11:37:34.205 + 00”,没有deleteDate。订阅C被视为有效期为2014年6月,直至当月。

这是我尝试的:

select "Month", sum(sub) over (order by "Month" asc) as "Active subscriptions"
from
(select to_char(subscriptions."creationDate" at time zone '-7', 'YYYY-MM') as "Month", 
    count(distinct subscriptions.id) as sub
    from subscriptions
    where (to_char(subscriptions."deletionDate" at time zone '-7', 'YYYY-MM') is null 
        or to_char(subscriptions."deletionDate" at time zone '-7', 'YYYY-MM') >= to_char(subscriptions."creationDate" at …
Run Code Online (Sandbox Code Playgroud)

postgresql timestamp cumulative-sum

3
推荐指数
1
解决办法
435
查看次数

每天查询计数,包括多周的日期限制

我每天都在努力寻找#活跃用户.

用户在连续 4 每周发出超过 10个请求时处于活动状态.

即.2014年10月31日,如果用户每周总共发出超过10个请求,则用户处于活动状态:

  1. 2014年10月24日至10月30日AND
  2. 2014年10月17日至10月23日AND
  3. 2014年10月10日至10月16日AND
  4. 2014年10月3日至10月9日

我有一张桌子requests:

CREATE TABLE requests (
  id text PRIMARY KEY, -- id of the request
  amount bigint,       -- sum of requests made by accounts_id to recipient_id,
                       -- aggregated on a daily basis based on "date"
  accounts_id text,    -- id of the user
  recipient_id text,   -- id of the recipient
  date timestamp       -- date that the request was made in YYYY-MM-DD
);
Run Code Online (Sandbox Code Playgroud)

样本值:

INSERT …
Run Code Online (Sandbox Code Playgroud)

sql postgresql date aggregate-functions postgresql-9.3

3
推荐指数
1
解决办法
1301
查看次数