起初,为了计算电梯带来的溢价,我直接用房源的 price (成交单价) 减去 communityAverage (小区均价),然后按是否有电梯进行 GROUP BY。
初版 SQL 结果出来后,我惊呆了: 计算出的溢价竟然是负值,甚至无电梯的均价高于有电梯的均价!
1 2 3 4 5 6 7
with new_biao as ( select id,price,communityAverage,(price - communityAverage) as premium_per_sqm,elevator,ladderRatio from real_estate_db.beijing_house_sales where communityAverage >0and communityAverage isnot null and price > 0) select elevator as `是否有电梯`,count(*) as `成交样本量`, avg(premium_per_sqm) as avg_price from new_biao group by elevator
with new_biao as ( select id,Cid,price,tradeTime,buildingStructure,elevator,ladderRatio,year(tradeTime) as tradeYear, avg(price) over (partitionby Cid,year(tradeTime)) as avg_price_that_yaer from real_estate_db.beijing_house_sales where price >0 ) select tradeYear as `交易年份`,elevator as `是否有电梯(1有/0无)`,`buildingStructure` as `建筑结构`,multiIf(ladderRatio<=0.33,'优质低密',ladderRatio<=0.5,'常规居住','高密塔楼') as ladder_type,count(*) as `成交样本量`, round(avg(price-avg_price_that_yaer),2) as `平均每平米溢价` from new_biao groupby tradeYear,elevator , `buildingStructure` ,ladder_type havingcount(*) >=50 orderby tradeYear,`buildingStructure`,elevator