sql - 在postgresql中计算百分比

标签 sql database postgresql percentage cumulative-sum

我有一个返回结果的查询

time  t_count  cumulative_t_count  zone  hour
_____ _____  _________________     ____  ____
1      10          10               1    1
2      20          30               1    1
3      30          60               1    1
4      60          120              1    1

我的查询会像

select time,t_count,sum(t_count) over (order by time) as
   cumulative_t_count ,zone,hour from (select distinct
   time,count(distinct num_id) as t_count,zone,hour from (select * from
   public.table1 where day=1 and time>0 order by time)as A group by
   time,hour,zone order by hour,zone )B where zone=1 and hour=1; 

现在我想要一个额外的列来显示这样的累积计数的百分比

time  t_count  cumulative_t_count  zone  hour   percentage_cumulative count
_____ _____  _________________     ____  ____   ____________________________
1      10          10               1     1                  10%
2      20          30               1     1                  30%
3      30          60               1     1                  60%
4      40          100              1     1                  100%

我试过

 select time,t_count,sum(t_count) over (order by time) as
       cumulative_t_count ,cumulative_t_count/sum(t_count) as percentage_cumulative count,zone,hour from (select distinct
       time,count(distinct num_id) as t_count,zone,hour from (select * from
       public.table1 where day=1 and time>0 order by time)as A group by
       time,hour,zone order by hour,zone )B where zone=1 and hour=1; 

但它没有用。感谢任何帮助。

最佳答案

为了计算每行累积计数占总累积计数的百分比,您应该对结果集运行另一个 SQL 并计算每行的百分比。

我相信查询应该能回答您要问的问题。

SELECT time,
t_count,
cumulative_t_count,
zone,
hour,
(((cumulative_t_count)/(sum(cumulative_t_count) OVER (ORDER BY time))) * 100) AS percentage_cumulative_count
FROM
(SELECT
  time,
  t_count,
  SUM(t_count) OVER (ORDER BY time) AS cumulative_t_count,
  zone,
  hour 
 FROM
  (
    SELECT DISTINCT
      time,
      COUNT(DISTINCT num_id) AS t_count,
      zone,
      hour
     FROM
      (
        SELECT
          * 
        FROM
          public.table1 
        WHERE
          day = 1 
          AND time > 0 
        ORDER BY
          time
      )
      AS a 
    GROUP BY
      time,
      hour,
      zone 
    ORDER BY
      hour,
      zone 
  ) b 
WHERE
  zone = 1 
  AND hour = 1) x;

关于sql - 在postgresql中计算百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41373394/

相关文章:

sql - 如何在Oracle 中打印出一个过程的定义?

sql - 仅返回在其他记录中具有匹配字段的记录

sql - 为什么 json_value 返回 null?

mysql - 获取即将到来的到期日期通知并在 SQL 中获取日期

ajax - 在 Postgres 中检索数据库的列和表

php - 如果此人存在则 MySQL 更新

java - 在数据库 Java Derby 中插入新数据时生成的 ID 错误

mysql - 组合两个 mysql Select 语句,以便我可以对结果数据进行排序

sql - PostgreSQL 第二个查询基于第一个查询的数组类型结果。即用数组链接查询

ruby-on-rails-3 - PgHero Rails - 列 "pid"不存在