【问题标题】:How to compare dates across two tables where one date is valid until updated?如何比较两个表的日期,其中一个日期在更新之前有效?
【发布时间】:2016-04-06 05:45:34
【问题描述】:

我有一个比较复杂的查询要写;我们使用 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 的节目 23 的 50 美元价格提醒,因为当用户创建此价格提醒时,low_price 已升至 60 美元。另请注意,每个ticket_seller 对于每张门票都有自己的low_price;答案需要找到在警报创建日期之前创建的任何票务供应商提供的最低价格。价格在更新之前一直有效,因此卖家 2 可在 2015 年 8 月 22 日为表演 23 提供的最低价格为 60 美元,因为这是当时的最低价格。

我们将不胜感激!

【问题讨论】:

  • 您使用的是哪个 DBMS?
  • 为什么 user_id=26 不能成为结果的一部分?该行创建于同一日期,价格与 user_id=25 相同
  • @a_horse_with_no_name 你是完全正确的! user_id=26 应该包括在内。我们正在使用 Postgres。

标签: sql postgresql rails-postgresql


【解决方案1】:

试试这个:

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))

这里可以使用特定于供应商的窗口函数,但您没有使用您正在使用的数据库标记您的问题,所以这是香草版本。

【讨论】:

  • 谢谢!这让我足够接近,可以自己弄清楚剩下的路。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 2011-01-13
  • 1970-01-01
  • 2012-10-25
相关资源
最近更新 更多