【发布时间】:2014-11-12 09:59:52
【问题描述】:
说明
考虑PostgreSQL 9.3 数据库中的下表:
Table "public.users"
Column | Type | Modifiers
--------------------+--------------------------+-----------------------------------------------------
sid | bigint | not null default nextval('users_sid_seq'::regclass)
creation_time | timestamp with time zone | default now()
...
我想生成一个时间戳之前创建的用户数量的报告,针对一系列时间戳,应该如下所示:
sampling_time | number_of_users |
---------------------+-------------------+
2014-11-01 00:00:00 | 100 |
2014-11-02 00:00:00 | 105 |
2014-11-03 00:00:00 | 110 |
2014-11-04 00:00:00 | 120 |
2014-11-05 00:00:00 | 125 |
2014-11-06 00:00:00 | 150 |
2014-11-07 00:00:00 | 201 |
2014-11-08 00:00:00 | 100 |
2014-11-09 00:00:00 | 250 |
2014-11-10 00:00:00 | 300 |
2014-11-11 00:00:00 | 400 |
我尝试过的
使用generate_series 可以轻松生成时间戳系列:
SELECT generate_series('2014-11-01'::timestamp,
'2014-11-11'::timestamp,
'1 day'::interval) AS sampling_time
查询
尝试将系列和用户上的COUNT(*) 组合失败:
SELECT * FROM
(SELECT generate_series('2014-11-01'::timestamp,
'2014-11-11'::timestamp,
'1 day'::interval)) AS sampling_time,
(SELECT COUNT(*)
FROM users
WHERE creation_time<=sampling_time)
AS created_before_sampling_time;
错误信息
ERROR: column "sampling_time" does not exist
LINE 7: WHERE creation_time<=sampling_time)
知道如何根据每行的samping_time 子查询用户计数吗?
【问题讨论】:
标签: sql postgresql subquery date-range