我有表格列;
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中构建查询来实现这个吗?
答案 0 :(得分:2)
您应该将字符串转换为数组并取消它们,然后您可以计算总数和百分比:
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)
答案 1 :(得分:2)
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