假设我在Postgres中有一个名为listings
的表,如下所示:
id neighborhood bedrooms price
1 downtown 0 256888
2 downtown 1 334000
3 riverview 1 505000
etc.
如何编写交叉表查询,将每间卧室的平均价格显示为列和邻域作为行?
查询的输出应该类似于这样(数字组成,列是卧室):
0 1 2 3
riverton 250000 300000 350000 -
downtown 189000 325000 - 450000
首先使用聚合函数avg()计算平均值:
SELECT neighborhood, bedrooms, avg(price)
FROM listings
GROUP BY 1,2
ORDER BY 1,2
然后按照相关答案中的详细说明将结果提供给crosstab()
函数:
在Postgres中构建数据透视表的最佳方法是Case语句。
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;
这是我的输出
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