Postgresql在特定时间间隔内创建的记录百分比

问题描述 投票:0回答:2

我有一个包含字段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:002019-04-30 00:00:00之间的时间间隔内创建的记录的百分比。在这个时间间隔,我有两个记录firstthird,所以结果应该是50%。我遇到了OVER()条款,但要么我不知道如何使用它,要么它不是我需要的。

sql postgresql percentage
2个回答
1
投票

我只想使用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'


2
投票

你可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.