postgres crosstab, ERROR: The provided SQL must return 3 columns

让人想犯罪 __ 提交于 2021-02-10 20:50:42

问题


Hello I have created a view, but want to pivot it.

OUTPUT before pivoting:

   tag1  |  qmonth1  |  qmonth2  |  sum1
 --------+-----------+-----------+--------
 name1   |  18-05   |  MAY      |  -166
 name2   |  18-05   |  MAY      |  -86
 name3   |  18-05   |  MAY      |  35
 name1   |  18-06   |  JUN      |  -102
 name2   |  18-06   |  JUN      |  -32
 name3   |  18-06   |  JUN      |  -75
 name1   |  18-09   |  AVG      |  -135
 name2   |  18-09   |  AVG      |  -52
 name3   |  18-09   |  AVG      |  -17

expected output:

 qmonth2 | name1 | name2 | name3
 --------+-------+-------+-------
  MAY    | -166  | -86  |  35
  JUN    | -102  | -32  | -75
  AVG    | -135  | -52  | -17

my full query:

SELECT tag1,qmonth2,sum1 FROM crosstab 
('SELECT tag1::text,qmonth1,qmonth2::text,sum1::numeric 
FROM public."chartdata_chart3"') 
AS ct ( "tag1" TEXT,"qmonth2" TEXT,"sum1" NUMERIC);

I getting this error and unable to resolve:

ERROR:  invalid source data SQL statement
DETAIL:  The provided SQL must return 3 columns: rowid, category, and values.
SQL state: 22023

回答1:


SQL statement passed as paremeter to crosstab() function must return one row_name column, one category column, and one value column. This in your case is qmonth2, tag1 and sum1.

This is your query considering sum1 is an integer, qmonth2 and tag1 are text:

select *
from crosstab(
  'select qmonth2, tag1, sum1
  from public."chartdata_chart3"
  ') AS ct(qmonth2 text, name1 int, name2 int, name3 int;

Output:

 qmonth2 | name1 | name2 | name3
---------+-------+-------+-------
 MAY     | -166  | -86   | 35
 JUN     | -102  | -32   | -75
 AVG     | -135  | -52   | -17

Refer to manual for more information and samples on how crosstab works.

Also, keep in mind that naming your columns/tables with quotes makes it more complex to write every SQL query so you are better off without doing that :)



来源:https://stackoverflow.com/questions/52151058/postgres-crosstab-error-the-provided-sql-must-return-3-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!