【问题标题】:Selecting pair(including reverse order) with highest date value选择日期值最高的对(包括倒序)
【发布时间】:2021-02-16 05:37:27
【问题描述】:

我有一个这样的消息表 Messages Table

我想选择日期最高的每个唯一对(包括倒序)。因此生成的 SQL Select 语句将是这样的:

from_id | to_id | date | message
1          2      13:06  I'm Alp
2          3      13:06  I'm Oliver
3          1      11:38  From third to one

我尝试将 distinct 与 max 函数一起使用,但没有帮助。

【问题讨论】:

    标签: sql sqlite datetime greatest-n-per-group


    【解决方案1】:

    你可以使用窗口函数:

    select *
    from (
        select m.*, 
            row_number() over(partition by min(from_id, to_id), max(from_id, to_id) order by date desc) rn
        from messages m
    ) m
    where rn = 1
    

    注意:与直觉相反,SQLite 的 min()max() 函数在给定多个参数时,等效于其他数据库中的 least()greatest()

    【讨论】:

    • 非常感谢,这确实有效!你能稍微解释一下你的代码吗?
    • @alpino:诀窍是通过成对的from/to 构建记录组。所以我们取这两列中的最小值和最大值来构建组。基本上,1/22/1 最终属于同一组。然后我们只取每组的最新记录。
    猜你喜欢
    • 2011-08-26
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    相关资源
    最近更新 更多