【问题标题】:Postgresql percentage of records created in the specific time intervalPostgresql 在特定时间间隔内创建的记录百分比
【发布时间】:2019-09-17 22:53:18
【问题描述】:

我有一个包含字段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() 子句,但要么我不知道如何使用它,要么它不是我需要的。

【问题讨论】:

  • 我删除了plpgsql 标签,因为它仅在您使用language plpgsql 编写存储函数(或过程)时才相关。它与“普通”SQL 查询无关
  • @a_horse_with_no_name 但如果答案将包括使用 plpgsql 的存储过程,我可以。

标签: sql postgresql percentage


【解决方案1】:

你可以使用 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

【讨论】:

  • 哇,这比我以前用谷歌搜索的要容易得多。非常感谢!
【解决方案2】:

我只会使用avg():

select avg( (created_at between '2019-04-28' and '2019-04-30')::int )
 from your_table

如果你想要一个介于 0 和 1 之间的值,你可以乘以 100。

我强烈建议您不要将 between 与日期/时间值一起使用。时间组件可能不会按照您想要的方式运行。你在你的问题中使用了“between”,但我把它留在了。但是,我建议:

select avg( (created_at >= '2019-04-28' and 
             created_at < '2019-04-30'
            )::int
          )
 from your_table;

不清楚是要&lt; '2019-04-30'&lt;= '2019-04-30'还是'2019-05-01'

【讨论】:

  • 这个看起来很优雅。如果我在查询中也使用where 子句,avg() 会正常工作吗?
  • @SergiiBishyr 。 . .是的。 where 在计算平均值之前过滤行。
猜你喜欢
  • 2011-12-14
  • 2017-02-21
  • 1970-01-01
  • 2015-11-06
  • 1970-01-01
  • 1970-01-01
  • 2022-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多