计算postgres中列数据的百分比

Calculate the percentage of column data in postgres

我有 table 列喜欢;

Documents
------------
1 2 3
1 2
2 3
1
4 5 1 3

文档栏下的数据表示文档的类型;例如

1 indicates passport
2 indicates School id  and so on.....

我希望列数据作为具有百分比计算的单独数据。喜欢;

基本上我想显示每个数据的百分比...

    Documents     percentage
    -------------------------
    1               10%
    2               2%
    3               1% 
    4               25%
    5               30%

我想将数据显示为单独的数据及其百分比。

我们可以在 postgres 中构建查询来实现这个吗????

您应该将字符串转换为数组并取消嵌套,然后您可以计算总数和百分比:

create table test (documents text);
insert into test values
('1 2 3'),
('1 2'),
('2 3'),
('1'),
('4 5 1 3');

with docs as (
    select doc
    from test, unnest(string_to_array(documents, ' ')) doc
    ),
total as (
    select count(*) as total
    from docs
    )
select doc, count(doc), count(doc)* 100/ total as percentage
from docs, total
group by doc, total
order by 1;

 doc | count | percentage 
-----+-------+------------
 1   |     4 |         33
 2   |     3 |         25
 3   |     3 |         25
 4   |     1 |          8
 5   |     1 |          8
(5 rows)    
with t(s) as ( values
    ('1 2 3'),('1 2'),('2 3'),('1'),('4 5 1 3')
)
select distinct s,
    count(*) over(partition by s) * 100.0 /
    count(*) over() as percentage
from (
    select regexp_split_to_table(s, ' ') as s
    from t
) t
;
 s |     percentage      
---+---------------------
 5 |  8.3333333333333333
 4 |  8.3333333333333333
 3 | 25.0000000000000000
 1 | 33.3333333333333333
 2 | 25.0000000000000000