【问题标题】:Get value from second highest row, join SQL从第二高行获取值,加入 SQL
【发布时间】:2015-11-09 00:00:20
【问题描述】:

我有两张桌子

排名

列:category_id、country_id、item_name、rank、created_at、updated_at、change

Pk: (category_id,country_id,rank)

Ranking_History

id、category_id、country_id、item_name、rank、created_at、updated_at

PK: id

排名表包含当前排名,排名历史表包含过去的所有排名。排名每天更新,我无法弄清楚自上次排名以来排名变化的sql查询。 change 需要在排名表中更新。

我尝试过加入表格,但我只需要排名历史表中的一行,但在加入期间我无法限制。

【问题讨论】:

  • 我不明白你的问题,更具体地说,change 是什么。考虑添加说明您的输入和所需输出的示例数据。
  • 你的主键应该使用item_name,而不是rank
  • @GordonLinoff 为什么是 item_name? (rank, category_id, country_id) 也是唯一的,每个rank只有一项。
  • 在此处考虑表架构调整。为什么要在不同的相关表中记录两次 ids、item_name 和 rank?对不同的项目和多个等级(一对多)进行规范化,并避免重复列。
  • @rajat 。 . . ranking 是随时间变化的计算。 item_name 作为表的主键似乎更为基础。

标签: sql postgresql


【解决方案1】:

一种方法是使用日期函数。像这样的:

update ranking r
    set change = (r.rank = rh.rank)
    from ranking_history rh
    where r.category_id = rh.cateogry_id and
          r.country_id = rh.country_id and
          r.item_name = rh.item_name and
          date_trunc('day', r.created_at) = date_trunc('day', rh.created_at + interval '1 day');

【讨论】:

    猜你喜欢
    • 2019-07-01
    • 2013-09-15
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多