【问题标题】:Join with multiple columns from two tables加入两个表中的多个列
【发布时间】:2017-08-19 14:42:55
【问题描述】:

我有两张桌子。第一个表名为 price_changes,另一个表名为 areaprice_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 是文本。

area 的下一个表的结构如下:

**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 列。

我尝试使用嵌套查询来做到这一点,但没有成功。我提出的嵌套查询是

从 fast_course_reg.price changes 中选择 listing_id,其中 new_price > old_price 和 change_date 像'2016%'和listing_id (从built_area > 200 或used_area > 200 的区域中选择listing_id);

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

【问题讨论】:

  • 编辑您的问题并显示您所做的尝试。

标签: mysql sql join


【解决方案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;

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2022-12-24
    • 2014-11-22
    相关资源
    最近更新 更多