【问题标题】:SQL group by from one table and max from anotherSQL group by 从一个表和 max 从另一个表
【发布时间】:2020-12-26 02:04:48
【问题描述】:

我有 3 张桌子 abbcdc。现在我想从ab 表中按a_id 分组,并从c 表中选择最大date。这是我到目前为止所尝试的:

select ab.a_id, bcd.d_id, c.val, max(c.date) as date
from tableab ab, tablebcd bcd, tablec c
where ab.b_id = bcd.b_id
and bcd.c_id = c.c_id
group by ab.a_id

它的工作没有错误,但没有给出正确的结果。我不太了解 SQL,所以我可能会遗漏一些简单的东西。感谢您的帮助!

【问题讨论】:

  • 你得到的结果是什么,你期望的结果是什么?
  • 文本格式的具有预期结果的示例数据会很有帮助。
  • @aRvi 我想要每个ab.a_id 一行(最大c.date 的那一行),但我得到了多行

标签: mysql sql datetime greatest-n-per-group window-functions


【解决方案1】:

从您现有的查询开始,直接的方法是row_number()(仅在 MySQL 8.0 中可用)。

select * 
from (
    select 
        ab.a_id, 
        bcd.d_id, 
        c.val, 
        row_number() over(partition by ab.a_id order by c.date desc) as rn
    from tableab ab
    iner join tablebcd bcd on  ab.b_id = bcd.b_id
    inner join tablec c on bcd.c_id = c.c_id
) t
where rn = 1 

row_number() 对具有相同 a_id 的记录按降序排列 date - 然后您可以使用此信息过滤表。

请注意,我重写了查询以使用标准的显式连接,而不是老式的隐式连接(在 from 子句中使用逗号):这种几十年前的语法不应该在新代码中使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多