【问题标题】:SQL - Multiple criteria MAX statementSQL - 多条件 MAX 语句
【发布时间】:2017-11-20 20:55:45
【问题描述】:

我有一个包含数百万行的表,每行都有一个时间戳。我需要一个语句来检查代码和日期条目并找到两者的最新时间戳。我尝试了以下查询,但收到错误“在 t 中找不到列行号”。

select 
code, date, other_crit1, other_crit2, timestamp
from (select ROW_NUMBER() over (partition by code order by date desc, timestamp desc)
    code, date, other_crit1, other_crit2, timestamp
    from MyTable) t
where RowNumber = 1

我觉得我很接近但并不完全在那里。任何帮助将不胜感激。

【问题讨论】:

    标签: sql max multiple-columns


    【解决方案1】:

    您需要为该列命名。我用seqnum:

    select code, date, other_crit1, other_crit2, timestamp
    from (select row_number() over (partition by code order by date desc, timestamp desc) as seqnum,
                 code, date, other_crit1, other_crit2, timestamp
          from MyTable
         ) t
    where seqnum = 1;
    

    如果你愿意,你可以叫它RowNumber。我对这个名字并不感兴趣,因为 SQL 结果集是无序的,除非有明确的order by 子句。

    【讨论】:

    • 超级接近@gordonlinoff。我看到的唯一问题是它没有看到每个时间戳的代码和日期的每个实例。
    • 我想通了。我在分区中添加了日期。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    相关资源
    最近更新 更多