Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql WITH clause in crosstab queries

I create a large query as a Common Table Expression - month_index using WITH clause. Is it possible to refer this Common Table Expression in a crosstab query's source sql?

When I did gets an error relation "month_index" does not exist

WITH month_index AS
(
      SELECT ...
)
SELECT * FROM CROSSTAB(
   'SELECT rowid AS row_name,
   CONCAT(''m'',monthno) AS category,
   nic5dindex AS value
   FROM month_index',
   '*<categorysql>*')
AS ct(..)

I use Postgresql 9.3.

like image 240
Thara Avatar asked Aug 12 '15 17:08

Thara


People also ask

IS WITH clause supported in PostgreSQL?

How WITH Clause works in PostgreSQL? We can specify the column list by using the common table expression in PostgreSQL. We can also join the table by using a clause in PostgreSQL. We have also use the recursive with a clause in the query.

How does crosstab work in Postgres?

The crosstab function produces one output row for each consecutive group of input rows with the same row_name value. The output row_name column, plus any “extra” columns, are copied from the first row of the group. The output value columns are filled with the value fields from rows having matching category values.

Does CTE work in Postgres?

In PostgreSQL, the CTE(Common Table Expression) is used as a temporary result set that the user can reference within another SQL statement like SELECT, INSERT, UPDATE or DELETE. CTEs are temporary in the sense that they only exist during the execution of the query.


1 Answers

You want to have your CTE fully contained within the crosstab. More like this... you can have a CTE in a crosstab, but not vice-versa.

    SELECT * 
FROM CROSSTAB(
$$
    WITH month_index AS
    (
       SELECT rowid AS row_name,
       CONCAT(''m'',monthno) AS category,
       nic5dindex AS value
       FROM source_data_table
    )
    SELECT * FROM month_index 
,
   '*<categorysql>*'
$$   
   )
AS ct(..)
like image 91
user3232196 Avatar answered Oct 22 '22 03:10

user3232196