我有一个相对复杂的查询要写;我们使用Postgres。基本上,我有两个表的数据:
表1:历史票价
ticket_seller_id | show_id | low_price | created_at
1 | 17 | 40 | 05/09/2015
2 | 23 | 50 | 06/23/2015
2 | 23 | 60 | 07/23/2015
2 | 23 | 70 | 08/23/2015
3 | 23 | 55 | 07/22/2015
表2:成员创建的价格警报
show_id | Price | user_id | created_at
17 | 40 | 25 | 02/16/2016
17 | 40 | 26 | 02/16/2016
23 | 50 | 25 | 07/24/2015
我想要做的是:创建一个结果表,其中只有“警报价格”低于现有历史价格的价格警报。从上面的数据来看,它看起来像这样:
show_id | Price | user_id | created_at
17 | 40 | 25 | 02/16/2016
请注意,用户25的show 23的50美元价格警报将不会显示,因为在用户创建此价格提醒时,low_price已上涨至$ 60。另请注意,每个ticket_seller都有自己的每个票证的low_price;答案需要找到任何故障单供应商提供的最低价格,该价格是在创建警报之前的日期创建的。价格在更新前有效,因此2015年8月22日卖家2的展示23的最低价格为60美元,因为这是当时的最低价格。
任何和所有帮助将不胜感激!
答案 0 :(得分:0)
试试这个:
select show_id, price, user_id, created_at
from price_alerts
where price < (
select price
from ticket_history
where show_id = price_alerts.show_id
and created_at = (
select max(created_at)
from ticket_history
where show_id = price_alerts.show_id
and created_at < price_alerts.created_at))
这里可以使用特定于供应商的窗口函数,但是您没有使用您正在使用的数据库标记您的问题,因此这是vanilla版本。