首页 > 解决方案 > Postgresql 在特定时间间隔内创建的记录百分比

问题描述

我有一个包含字段的表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。在这个时间间隔内,我有两条记录firstthird,所以结果应该是50%。我遇到了该OVER()子句,但要么我不知道如何使用它,要么它不是我需要的。

标签: sqlpostgresqlpercentage

解决方案


您可以使用案例

 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

推荐阅读