postgresql 计算百分比

hpxqektj  于 2023-01-05  发布在  PostgreSQL
关注(0)|答案(3)|浏览(384)

我想更新下面提到的表格,如

rate = round(score / sum(score) * 100, 2)

+-------+------+
| score | rate |
+-------+------+
|    49 |    0 |
|    27 |    0 |
|    26 |    0 |
|    28 |    0 |
|     7 |    0 |
|     6 |    0 |
|     7 |    0 |
|    13 |    0 |
|    12 |    0 |
|    13 |    0 |
|    13 |    0 |
|     3 |    0 |
|     6 |    0 |
|    13 |    0 |
|     5 |    0 |
|     5 |    0 |
|    10 |    0 |
|   707 |    0 |
+-------+------+

结果应该是这样的

+-------+-------+
| score | rate  |
+-------+-------+
|    49 | 5.16  |
|    27 | 2.84  |
|    26 | 2.74  |
|    28 | 2.95  |
|     7 | 0.74  |
|     6 | 0.63  |
|     7 | 0.74  |
|    13 | 1.37  |
|    12 | 1.26  |
|    13 | 1.37  |
|    13 | 1.37  |
|     3 | 0.32  |
|     6 | 0.63  |
|    13 | 1.37  |
|     5 | 0.53  |
|     5 | 0.53  |
|    10 | 1.05  |
|   707 | 74.42 |
+-------+-------+

我尝试使用此代码和其他一些代码,但结果为0

update table1 
set rate = round((score / (select sum(score) 
                           from table1) * 100)::numeric, 2);

Here is the link of demo table

hgtggwj0

hgtggwj01#

您需要将总和强制转换为数字以强制进行数字除法

update table1 set rate=round((score::numeric/(select sum(score) from table1)*100)::numeric,2);
h7appiyu

h7appiyu2#

试试这个:

SELECT score
     , round((score :: numeric / sum(score) OVER ()) * 100, 2)
  FROM your_table

如果score是整数,则必须转换为数字、实数或双精度,以便不会得到0作为结果。
sum必须在此处用作window function,以便计算所有现有行的总和。
如果要更新your_table的rate列:

UPDATE your_table t1
   SET rate = t2.rate
  FROM 
     ( SELECT score, round((score :: numeric / sum(score) OVER ()) * 100, 2) AS rate
         FROM your_table
     ) AS t2
 WHERE t1.score = t2.score

这里需要FROM子句,因为UPDATE不接受SET子句中的聚合函数和窗口函数。
参见dbfiddle

vkc1a9a2

vkc1a9a23#

您也可以将CTE与窗口函数一起使用;

WITH my_rates AS (
  SELECT DISTINCT
      score, 
      (score::NUMERIC * 100 / sum(score::NUMERIC) over())::NUMERIC(4,2) rate
    FROM table1
)
UPDATE table1 t SET 
    rate = my_rates.rate
  FROM my_rates
  WHERE
    my_rates.score = t.score

这是fiddle

相关问题