如何比较两个表中的日期,其中一个日期在更新之前有效?
How to compare dates across two tables where one date is valid until updated?
我有一个比较复杂的查询要写;我们使用 Postgres。基本上,我有两个 table 的数据:
Table 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
Table 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
我想做的是:创建一个结果 table,其中只有 "alert price" 低于现有历史价格的价格提醒。从上面的数据来看,它看起来像这样:
show_id | Price | user_id | created_at
17 | 40 | 25 | 02/16/2016
请注意,不会显示来自用户 25 的节目 23 的 50 美元价格提醒,因为在用户创建此价格提醒时,low_price 已升至 60 美元。另请注意,每个 ticket_seller 每张票都有自己的 low_price;答案需要找到任何票务供应商提供的最低价格,该价格是警报创建日期之前 created_at 的日期。价格在更新前一直有效,因此卖家 2 提供的节目 23 的最低价格在 2015 年 8 月 22 日为 60 美元,因为那是当时的最低价格。
如有任何帮助,我们将不胜感激!
试试这个:
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))
可以在此处使用特定于供应商的 window 函数,但您尚未使用正在使用的数据库标记您的问题,因此这是原始版本。
我有一个比较复杂的查询要写;我们使用 Postgres。基本上,我有两个 table 的数据:
Table 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
Table 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
我想做的是:创建一个结果 table,其中只有 "alert price" 低于现有历史价格的价格提醒。从上面的数据来看,它看起来像这样:
show_id | Price | user_id | created_at
17 | 40 | 25 | 02/16/2016
请注意,不会显示来自用户 25 的节目 23 的 50 美元价格提醒,因为在用户创建此价格提醒时,low_price 已升至 60 美元。另请注意,每个 ticket_seller 每张票都有自己的 low_price;答案需要找到任何票务供应商提供的最低价格,该价格是警报创建日期之前 created_at 的日期。价格在更新前一直有效,因此卖家 2 提供的节目 23 的最低价格在 2015 年 8 月 22 日为 60 美元,因为那是当时的最低价格。
如有任何帮助,我们将不胜感激!
试试这个:
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))
可以在此处使用特定于供应商的 window 函数,但您尚未使用正在使用的数据库标记您的问题,因此这是原始版本。