在 PostgreSQL 9.0 中创建 crosstab() 数据透视表

dan*_*lin 5 postgresql pivot postgresql-9.0

我自己有一个相当复杂的问题,我希望有人可以帮助我。

我想使用 PostgreSQL 来从无几何表创建数据透视表。

为了简单起见,我将只显示我想要用于枢轴的表结构,然后使用给出的方法来创建其他表结构,我希望:)

我想使用的字段是postcode_nospace_, 和ageband

ageband顶部的列是行,postcode_nospace_每个邮政编码的计数是数据。

有 2132 条记录,其中一些记录有多个邮政编码,因此计数。

CREATE TABLE adult_social_care.activities_in_localities_asc
(
  ogc_fid integer NOT NULL,
  sort numeric(5,0),
  ageband character(12),
  postcode_nospace_ character(8),
  wkb_geometry geometry,
  CONSTRAINT activities_in_localities_asc_pkey PRIMARY KEY (ogc_fid)
);
Run Code Online (Sandbox Code Playgroud)

更新:

这是我想要实现的结果,如具有相同数据的 Excel 数据透视表所示。

postcode 18_24  25_34   35_44   45_54   55_64   65_74   Total Count
----------------------------------------------------------------------------
BB115DE     1           2                   2      3       8
FY38LZ                              1       1              2
Run Code Online (Sandbox Code Playgroud)

通过环顾四周,我编译了以下 SQL 查询。它按邮政编码分组并创建所需的字段名称。但是这些字段是空白的。理想情况下,我还希望total_count在表格末尾有一列。

SELECT * FROM crosstab(
    'SELECT postcode_nospace_, ageband, count(ageband) as total_count
     FROM adult_social_care.activities_in_localities_asc
     GROUP BY postcode_nospace_, ageband
     ORDER BY postcode_nospace_'

     ,$$VALUES ('18-24'::text), ('25-34'), ('35-44'), ('45-54'), ('55-64'), ('65-74'), ('75-84'), ('85-94'), ('95 AND OVER')$$)
AS ct("postcode" text, "18-24" numeric, "25-34" numeric,"35-44" numeric, "45-54" numeric, "55-64" numeric, "65-74" numeric, "75-84" numeric, "85-94" numeric, "95 AND OVER" numeric);
Run Code Online (Sandbox Code Playgroud)

dez*_*zso 5

你的表定义说

...
ageband character(12),
...
Run Code Online (Sandbox Code Playgroud)

这意味着那里的值看起来像'18-24 '而不是'18-24'. 这样,VALUES列表中的项目与表中的值不匹配,因此您会得到一个空表作为结果。

如果将列类型更改为更有意义text(正如 Erwin 指出的那样,这也会修剪值):

ALTER TABLE activities_in_localities_asc ALTER COLUMN ageband TYPE text;
Run Code Online (Sandbox Code Playgroud)

你会得到你想要的结果。

  • @danielfranklin:请为新问题提出一个新问题。评论不是地方。您始终可以链接到此链接以获取上下文。 (3认同)