簡體   English   中英

與來自兩個表的多個列聯接

[英]Join with multiple columns from two tables

我有兩張桌子。 第一個表命名為price_changes ,而另一個表命名為area 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是文本形式。

下表是area的結構,如下所示:

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

這里listing_idBuilt_areaused_area都是整數值。

我要進行而無法執行的Sql查詢是這樣的:

計算2016年價格上漲的已建成或使用面積> 200的房地產的平均平方米價格。在這里,平均平方米價格將意味着將build_areaused_area求和以形成一個名為total_area的新列,而對於價格,我必須使用created_price列。

我嘗試使用嵌套查詢來完成此操作,但未成功。 我出現的嵌套查詢是

從fast_course_reg中選擇listing_id。 price changes ,其中new_price> old_price和change_date如'2016%'和listing_id(在building_area> 200或used_area> 200的區域中選擇listing_id);

但是問題是嵌套查詢不允許在嵌套部分中添加多個列。 使用Join,我不知道該怎么做,因為內部聯接不允許從兩個表中選擇多個列。

獲取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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM