使用 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/