在特定时间间隔内创建的 Postgresql 记录百分比
Postgresql percentage of records created in the specific time interval
我有一个包含字段 created_at
的 table。我想计算在指定时间间隔内创建的记录总数的百分比。假设我有以下结构:
| name | created_at |
----------------------------------------
| first | "2019-04-29 09:30:07.441717" |
| second | "2019-04-30 09:30:07.441717" |
| third | "2019-04-28 09:30:07.441717" |
| fourth | "2019-04-27 09:30:07.441717" |
所以我想计算在 2019-04-28 00:00:00
和 2019-04-30 00:00:00
之间的时间间隔内创建的记录的百分比是多少。在这个时间区间内,我有两条记录first
和third
,所以结果应该是50%
。我遇到了 OVER()
子句,但要么我不知道如何使用它,要么它不是我需要的。
你可以使用CASE
select 100 * count(case
when created_at between '2019-04-28 00:00:00' and '2019-04-30 00:00:00'
then 1
end) / count(*)
from your_table
我只会使用 avg()
:
select avg( (created_at between '2019-04-28' and '2019-04-30')::int )
from your_table
如果你想要一个介于 0 和 1 之间的值,你可以乘以 100。
我强烈建议您不要将 between
与 date/time 值一起使用。时间组件可能不会按照您想要的方式运行。您在问题中使用了 "between",但我将其保留。但是,我建议:
select avg( (created_at >= '2019-04-28' and
created_at < '2019-04-30'
)::int
)
from your_table;
不清楚你想要< '2019-04-30'
、<= '2019-04-30'
还是'2019-05-01'
。
我有一个包含字段 created_at
的 table。我想计算在指定时间间隔内创建的记录总数的百分比。假设我有以下结构:
| name | created_at |
----------------------------------------
| first | "2019-04-29 09:30:07.441717" |
| second | "2019-04-30 09:30:07.441717" |
| third | "2019-04-28 09:30:07.441717" |
| fourth | "2019-04-27 09:30:07.441717" |
所以我想计算在 2019-04-28 00:00:00
和 2019-04-30 00:00:00
之间的时间间隔内创建的记录的百分比是多少。在这个时间区间内,我有两条记录first
和third
,所以结果应该是50%
。我遇到了 OVER()
子句,但要么我不知道如何使用它,要么它不是我需要的。
你可以使用CASE
select 100 * count(case
when created_at between '2019-04-28 00:00:00' and '2019-04-30 00:00:00'
then 1
end) / count(*)
from your_table
我只会使用 avg()
:
select avg( (created_at between '2019-04-28' and '2019-04-30')::int )
from your_table
如果你想要一个介于 0 和 1 之间的值,你可以乘以 100。
我强烈建议您不要将 between
与 date/time 值一起使用。时间组件可能不会按照您想要的方式运行。您在问题中使用了 "between",但我将其保留。但是,我建议:
select avg( (created_at >= '2019-04-28' and
created_at < '2019-04-30'
)::int
)
from your_table;
不清楚你想要< '2019-04-30'
、<= '2019-04-30'
还是'2019-05-01'
。