2017-08-19 57 views
0

我有两个表。第一个表格命名为price_changes其中另一个名称为区域。的price_changes结构为:加入两个表中的多列

**listing_id** **old_price** **new_price** **change_date** 
240509   180999  100234  2016-03-30 
230599   165789  189760  2017-06-12 
245678   123456  176432  2016-12-08 

这里listing_idOLD_PRICENEW_PRICE是整数,而CHANGE_DATE是文本。

下表是区域具有这样的结构:

**listing_id** **built_area**, **used_area** 
240509   340    0 
230599   0    789 
245678   125    175 

这里listing_idbuilt_areaused_area都是整数值。

,我想让而无法做到这一点的SQL查询是这样的:

计算与增加的价格属性的平均平方米的价格在2016年已经建成或使用面积> 200这里的平均平方米的价格就意味着既总结built_areaused_area,形成所谓的total_area新列和价格,我不得不使用increased_price列。

我试图用嵌套查询来做,但没有成功。我想出的嵌套查询是

SELECT listing_id FROM fast_course_reg。 price changes其中new_price> old_price和change_date 如'2016%'和listing_id在 (从built_area> 200或used_area> 200的区域中选择listing_id);

但问题是嵌套查询不允许在嵌套部分添加多个列。有了Join,我不知道该怎么做,因为内部连接不允许从两个表中选择多个列。

+0

编辑你的问题,并显示你所做的尝试。 –

回答

1

要获得其价格在2016年增加的属性:

select listing_id, max(new_price) 
from price_changes 
where old_price < new_price and change_date >= '2016-01-01' and 
     change_date < '2017-01-01' 
group by listing_id; 

然后,您可以使用它作为一个子查询得到的平均值。结果是这样的:

select sum(new_price)/sum(built_area + used_area) 
from (select listing_id, max(new_price) as new_price 
     from price_changes 
     where old_price < new_price and change_date >= '2016-01-01' and 
      change_date < '2017-01-01' 
     group by listing_id 
    ) l join 
    area a 
    using (listing_id) 
where built_area > 200 or used_area > 200;