我有一个包含字段created_at
的表。我想根据在指定时间间隔内创建的总数来计算记录的百分比。假设我有以下结构:
| 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()
条款,但要么我不知道如何使用它,要么它不是我需要的。
我只想使用avg()
:
select avg( (created_at between '2019-04-28' and '2019-04-30')::int )
from your_table
如果你想要一个0到1之间的值,你可以乘以100。
我强烈建议您不要将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'
。
你可以使用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