从不完整的数据返回结果?

时间:2015-12-13 13:33:22

标签: sql postgresql plpgsql

我有两张大表avg_rentavg_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_salemedian_rentapartment_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

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以使用full outer joinCOALESCE

执行此操作
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_idavg_rent中的avg_sale个{} 如果您的apartment表格中包含所有apartment_size_id个信息,那么您可以使用left joinCOALESCE

执行相同操作
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

sql fiddle demo

答案 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。