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

标签 sql postgresql

使用 PostgreSQL 9.4.1,我尝试识别/显示 3 个不同列中值的出现情况。请参阅下文(对格式表示歉意,我无法获得正确的表格格式。Type、type1 和 type2 是列名称。表名称是 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   

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

最佳答案

您可以使用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

关于sql - PostgreSQL:显示和计算多列中不同值的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30091148/

相关文章:

sql - 单个查询删除并显示重复记录

python - 带有 JOIN 和 GROUP BY SQL 查询的 Django COUNT

sql - 在 Excel VBA 中使用长 Access SQL 查询

sql - 如何计算作为不同值总和的运行总计

postgresql - 如何使用 psycopg2 将 postgresql 的结果保存到 csv/excel 文件?

sqlite - 将单列 SQL SELECT 结果列表变成一行

postgresql - 有没有办法使用 order by 将相似的字段一起排序?

ruby-on-rails - rails : calculate stats and group by day

postgresql - 从 CSV 文件更新 PostgreSQL 表

ruby-on-rails - 用于过滤嵌套 has_many 关联的 ActiveRecord 查询