Create a pivot table with PostgreSQL

佐手、 提交于 2019-11-26 04:56:19

问题


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

回答1:


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



回答2:


The best way to build pivot tables in Postgres is Case statements.

select neighborhood,
round(avg((case when bedroom = 0 then price else 0 end)),2) as "0",
round(avg((case when bedroom = 1 then price else 0 end)),2) as "1",
round(avg((case when bedroom = 2 then price else 0 end)),2) as "2",
round(avg((case when bedroom = 3 then price else 0 end)),2) as "3",
from listings
group by neighborhood;

This was my output

NEIGHBORHOOD                  0          1          2          3
-------------------- ---------- ---------- ---------- ----------
downtown                      0     373.38     328.25     524.63
riverview                     0     256.83          0       1341
north                         0     199.15     507.85     986.31


来源:https://stackoverflow.com/questions/20618323/create-a-pivot-table-with-postgresql

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