【问题标题】:SQL - pull newest 1 record for given columnSQL - 为给定列提取最新的 1 条记录
【发布时间】:2020-10-05 15:28:20
【问题描述】:

我有以下查询,它可以很好地提取有关厨师、他们的菜单和他们出售的食品的信息。

但是,它缺少最后一列“last_order_placed”

此列需要从表“orders”中提取单个最新(最新)条目,列名“placed”。每个特定的商店 (store.id) 都会在每次销售该食品时在 orders.placed 中有一个值。

这是一个 postgresql 13 数据库。

我想添加一列以包含来自 orders.placed 的每个商店 (store.id) 的最新条目:

select distinct
account.id,
account.email,
account.firstname, 
account.lastname, 
account.phone, 
account.zip_code,
menu.name,
kitchen_item.name, 
kitchen_item.price,
kitchen_item.daily_max_orders,
menu.pickup_start_time, 
menu.pickup_end_time,
menu.repeat_mon,
menu.repeat_tues,
menu.repeat_wed,
menu.repeat_thurs,
menu.repeat_fri,
menu.repeat_sat, 
menu.repeat_sun,
from account
left join store on account.id = store.account_id
left join menu on store.id = menu.store_id
left join kitchen_item on store.id = kitchen_item.store_id
left join menu_item on (kitchen_item.id = menu_item.kitchen_item_id and menu.id = menu_item.menu_id)
left join orders on store.id = orders.store_id
where account.is_seller_fully_registered = True
and account.is_deleted = False
and menu.deleted = False
and menu_item.is_deleted = False
group by account.id, account.email, account.firstname, account.lastname, account.phone, account.zip_code, menu.name, kitchen_item.name, kitchen_item.price, kitchen_item.daily_max_orders, menu.pickup_start_time, menu.pickup_end_time, menu.repeat_mon, menu.repeat_tues, menu.repeat_wed, menu.repeat_thurs, menu.repeat_fri, menu.repeat_sat, menu.repeat_sun
order by account.id asc;

我不知道如何将其与所有其他联接合并。我已经尝试过其他帖子的建议,从我收集到的信息中,我应该在订单表的连接上实现这一点。 比如:

INNER JOIN (
             select MAX (orders.placed) last_order
             from orders o on orders.store_id = store.id
          )
        GROUP BY store.id

谁能帮帮我?

【问题讨论】:

  • 请提供样本数据和期望的结果。尚不清楚为什么当前查询首先需要distinct(更不用说distinctgroup by 充其量是多余的)。
  • 注意:and menu.deleted = False and menu_item.is_deleted = False 会将这两个左连接变成普通连接。
  • 感谢您的输入,不,我没有真正的理由需要使用 distinct 和 group by。提供带有一些示例数据的插入语句将是一项非常耗时的任务,但我会尽力提供。谢谢

标签: sql postgresql greatest-n-per-group


【解决方案1】:

如果我理解正确,你可以使用distinct on

select distinct on (store_id) . . .
. . .
order by store_id, o.placed desc

您可能不需要group by。至少,你的问题没有解释为什么它是必要的。

【讨论】:

  • 感谢您的意见。你是对的,因为我不需要使用 distinct 和 group by,这是我的错误。我将尝试使用您的方法对这个新的“last_order_placed”列使用子查询,但这不会从orders.placed 中检索每个项目吗?我正在尝试仅从 orders.placed 中为每个 store.id 检索最新(最新)值。
  • @boog 。 . .这就是这个逻辑应该做的。
  • 谢谢 gordon,我能够将您的逻辑实现到子查询中以完成我想要的输出。你又成功了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多