PostgreSQL:显示和计算多列中不同的值出现次数

时间:2015-05-07 02:56:04

标签: sql postgresql

使用PostgreSQL 9.4.1,我试图识别/显示3个不同列的值的出现。请参阅下文(格式化道歉,我无法获得正确的表格格式。类型,类型1和类型2是列名。表名是documents

CREATE TABLE documents
AS
  SELECT *
  FROM ( VALUES 
    ('USA','China','Africa'),
    ('China','USA','Chemicals'), 
    ('Chemicals','Africa','USA')
  ) AS t(type,type1,type2);

下面是表格中的\ d +:

     Column     |  Type  |                       Modifiers                        
----------------+--------+--------------------------------------------------------
 id             | bigint | not null default nextval('documents_id_seq'::regclass)
 title          | text   | 
 description    | text   | 
 source         | text   | 
 url            | text   | 
 emaillink      | text   | 
 emailurl       | text   | 
 type           | text   | 
 language       | text   | 
 author         | text   | 
 publisheddate  | date   | default ('now'::text)::date
 comments       | text   | 
 classification | text   | 
 submittedby    | text   | 
 localurl       | text   | 
 type1          | text   | 
 type2          | text   | 
Indexes:
    "documents_pkey" PRIMARY KEY, btree (id)

我想要一个返回的查询:

Africa - 2   
Chemicals - 2  
China - 2   
USA - 3   

这是一个可能会相当自由地运行的查询,因此我希望尽可能避免昂贵的查询。

3 个答案:

答案 0 :(得分:1)

您可以使用union all将列数据转换为行,然后执行分组计算每种类型的匹配项

select type, count(*) from (
    select type1 as type from mytable
    union all select type2 from mytable
    union all select type3 from mytable
) t1 group by type

答案 1 :(得分:1)

试试这个:

SELECT WORD, COUNT(1) OCCURENCES
FROM (
    SELECT Type FROM TableName
    UNION ALL
    SELECT Type1 FROM TableName
    UNION ALL
    SELECT Type2 FROM TableName)
GROUP BY WORD;

答案 2 :(得分:0)

或者,您可以使用ARRAY[]/unnest()

SELECT x, count(x)
FROM (
  SELECT ARRAY[type,type1,type2] AS array
  FROM documents
) AS t
CROSS JOIN LATERAL unnest(t.array)
  AS x
GROUP BY x;

     x     | count 
-----------+-------
 USA       |     3
 China     |     2
 Chemicals |     2
 Africa    |     2
(4 rows)