2016-06-30 5 views
0

私はテーブルの列を持っています。ポストグラムの列データの割合を計算します。

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

列が何種類あるの? – klin

+0

そのテキストタイプ.... –

+0

ドキュメントでは、この列構造ですか?詳細をいくつか挙げてください。正確に必要なものは何ですか? –

答えて

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 
+0

... thanks neto –

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)  
関連する問題