交叉表函数结果中的意外重复项

Unexpected duplicates in result of crosstab function

我是 Postgres 和函数 crosstab() 的新手。我有这样的查询:

select * from crosstab(
  'select artis_clean, release_year, total_count_song from top_artis_5year ' ,
   'select distinct release_year from top_artis_5year order by 1 '
    
) as (
 "artis_clean" text, "1965" int , "1966" int, "1967" int, "1968" int,"1969" int,"1970" int
);

我得到这样的结果:

artis_clean     1965    1966    1967    1968    1969    1970
------------    ----    ----    ----    ----    ----    -----
the beatles     null    null    23      null    null    null
led zepelin     null    null    null    null      18    null
the beatles       15    null    null    13        13    null
led zepelin       12    null    null    null    null    null
jimi hendrix    null    null    9       null    null    null
jimi hendrix       8    null    null    null    null    null

为什么我把artis_clean放在distinct里,artis_clean还是有重复的数据?

 'select distinct release_year,artis_clean from top_artis_5year order by 1 '

代码将无法工作,Postgres 说:

ERROR:  provided "categories" SQL must return 1 column of at least one row
SQL state: 42601

输入需要排序。将 ORDER BY 1 附加到第一个查询的第一个参数。

另外,当列定义列表是静态的时,为第二个参数动态查询所有 release_year 是没有意义的。

参见:

  • PostgreSQL Crosstab Query

要替换生成的 NULL 值,请在外部 SELECT 中使用 COALESCE。示例:

  • Use row values as columns in PostgreSQL