【问题标题】:SQL: Filter rows with max valueSQL:过滤具有最大值的行
【发布时间】:2014-07-12 14:27:38
【问题描述】:

这是我的表结构:

File    |   Version     |   Function
1       |   1           |   1
1       |   2           |   1
1       |   3           |   1
1       |   2           |   2

2       |   1           |   4
3       |   2           |   5

我需要它只返回这些行

1       |   3           |   1
2       |   1           |   4
3       |   2           |   5

意思是我只想要每个文件都有最新版本的函数。

我不想要下面的结果,即不是最新版本的唯一函数 ID

1       |   3           |   1
1       |   2           |   2
...

我查看了How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?,但它返回了最新的唯一函数 ID。

查询需要与 sqlite3 兼容。

【问题讨论】:

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


    【解决方案1】:

    执行此操作的有效方法通常是使用not exists

    select t.*
    from table t
    where not exists (select 1
                      from table t2
                      where t2.file = t.file and t2.Version > t.version
                     );
    

    此查询可以利用table(file, version) 上的索引。

    这将查询改写为:“从表中获取相应文件没有更大版本的所有行。”

    【讨论】:

    【解决方案2】:

    在 SQLite 3.7.11 或更高版本中,当你使用 MAX 时,其他值保证来自最大值的行:

    SELECT File,
           MAX(Version) AS Version,
           Function
    FROM MyTable
    GROUP BY File
    

    【讨论】:

      【解决方案3】:

      请注意,如果文件的整体最新版本存在于不同的功能,这将返回每个文件的多行。即,如果您上面的示例有一个额外的行 (1,3,2) 这将为文件 1 返回 2 行。

      select
          t1.file,
          t1.version,
          t1.function
      from 
          mytable t1
      join (
          select 
              t2.file,
              max(t2.version) max_version        
          from  mytable t2
          group by t2.file
      ) t3 join t1.file = t3.file and t1.version = t3.max_version
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多