我有两张大表avg_rent
和avg_sale
。它们包含按地点,公寓大小和其他因素细分的公寓的平均价格。这些表格中的数据可能不完整。
例如,在表avg_sale
中我可能有:
id | apartment_size_id | county | city | median_sale
100 | 1 | 1 | 4 | 800
101 | 4 | 1 | 4 | 600
102 | 6 | 1 | 4 | 650
在表avg_rent
中我可能有:
id | apartment_size_id | county | city | median_rent
300 | 1 | 1 | 4 | 300
301 | 2 | 1 | 4 | 250
302 | 3 | 1 | 4 | 200
303 | 4 | 1 | 4 | 250
305 | 6 | 1 | 4 | 200
我想创建一个SQL
查询或plpqsql
函数,该函数将汇总median_sale
,median_rent
和apartment_size_id
列,并用-1填充缺失的数据或者其他的东西。如果该示例将返回此(总共有6个大小类别):
apartment_size_id | median_rent | median_sale
1 | 300 | 800
2 | 250 | -1
3 | 200 | -1
4 | 250 | 600
5 | -1 | -1
6 | 200 | 650
我该怎么做?
答案 0 :(得分:2)
您可以使用full outer join
和COALESCE
select
r.apartment_size_id,
COALESCE(r.median_rent, -1) as median_rent,
COALESCE(s.median_sale, -1) as median_sale
from avg_rent r
FULL OUTER JOIN avg_sale s
on r.apartment_size_id = s.apartment_size_id
此查询肯定只提供apartment_size_id
和avg_rent
中的avg_sale
个{}
如果您的apartment
表格中包含所有apartment_size_id
个信息,那么您可以使用left join
和COALESCE
select
a.apartment_size_id,
COALESCE(r.median_rent, -1) as median_rent,
COALESCE(s.median_sale, -1) as median_sale
from apartment a
LEFT JOIN avg_rent r on a.apartment_size_id = r.apartment_size_id
LEFT JOIN avg_sale s on a.apartment_size_id = s.apartment_size_id
答案 1 :(得分:2)
如果你有一套公寓大小表,你可以使用left join
:
select a.apartment_size_id, coalesce(r.median_rent, -1) as median_rent,
coalesce(s.median_sales, -1) as median_sales
from apartment_sizes a left join
avg_rent r
on a.apartment_size_id = r.apartment_size_id and
r.county = 1 and r.city = 4 left join
avg_sale s
on a.apartment_size_id = s.apartment_size_id and
s.county = 1 and s.city = 4;
这也假定您需要单个县/城市对的信息。
我建议您使用NULL
而不是-1
来表示缺失的值,除非您有充分的理由选择-1。