我有两个表,分别代表客户产品及其竞争对手产品的数据库:
tmp_match
-from_product_id和to_product_id分别表示客户产品和竞争对手产品之间的匹配。
tmp_price_history
-显示每个日期每种产品的价格。
我正在尝试编写一个查询,该查询将列出表tmp_price_history
中的所有日期。对于每个日期,我都希望根据表tmp_match
中的产品匹配对查看客户产品价格与竞争对手产品价格之间的关系,而不管是否存在客户产品或竞争对手产品的价格历史记录或两者 >:
如果两个价格都可用于特定日期,请在它们的列中同时列出
如果只有客户产品的记录-仅显示客户价格(并将竞争对手列留空)。
如果只有竞争对手产品的记录,请在其栏中显示竞争对手的价格。
预期结果:
date from_product_id to_product_id cust_price comp_price
1 1 11 99 95
2 1 11 98 94
1 1 12 92
2 1 12 91
2 2 108
我尝试使用以下查询来实现这一目标:
select cust_hist.date, from_product_id, to_product_id, cust_hist.price as cust_price,comp_hist.price as comp_price
from tmp_match as matches
left join tmp_price_history cust_hist
on cust_hist.product_id = matches.from_product_id
left join tmp_price_history comp_hist
on comp_hist.product_id = matches.to_product_id
;
但是它无法实现我的目标,如本sql snippet所示。