Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a pivot table with PostgreSQL

Tags:

Suppose I have a table in Postgres called listings that looks like this:

id    neighborhood    bedrooms    price 1     downtown        0           256888 2     downtown        1           334000 3     riverview       1           505000 etc. 

How do I write a crosstab query that shows the average price per bedrooms as the columns and neighborhoods as the rows?

The output of the query should look something like this (numbers are made up, columns are the bedrooms):

            0       1       2       3 riverton    250000  300000  350000  - downtown    189000  325000  -       450000 
like image 242
Avishai Avatar asked Dec 16 '13 18:12

Avishai


People also ask

Does PostgreSQL have PIVOT function?

SQL Server provides PIVOT and UNPIVOT functions to create pivot tables. Unfortunately, PostgreSQL does implement them. However, it provides crosstab function from tablefunc extensions which is equivalent to PIVOT .

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.


1 Answers

First compute the average with the aggregate function avg():

SELECT neighborhood, bedrooms, avg(price) FROM   listings GROUP  BY 1,2 ORDER  BY 1,2 

Then feed the result to the crosstab() function as instructed in great detail in this related answer:

  • PostgreSQL Crosstab Query
like image 72
Erwin Brandstetter Avatar answered Sep 19 '22 04:09

Erwin Brandstetter