如何仅选择 SQL 中具有不同版本的文档列表的最大版本? [英] How do you select only the maximum version of a list of documents that have different versions in SQL?

查看:32
本文介绍了如何仅选择 SQL 中具有不同版本的文档列表的最大版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据库表:

I have a database table that looks like this:

| ID | TITLE | VERSION | 
| 1  | file1 |    1    |
| 2  | file2 |    1    |
| 3  | file1 |    2    |
| 4  | file2 |    2    |

我需要一个将返回第 3 行和第 4 行的 SQL 查询,因为它们是文件 1 和文件 2 的最新版本.

I need an SQL query that will return rows 3 and 4 because they are the latest versions of file1 and file 2.

如果我在一个看起来像这样的表上运行查询:

If I run the query on a table that looks like this:

| ID | TITLE | VERSION | 
| 1  | file1 |    1    |
| 2  | file2 |    1    |
| 3  | file1 |    2    |
| 4  | file2 |    2    |
| 5  | file3 |    1    |

它应该返回第 3,4 和 5 行,因为file3"version1 是 file3 的最新版本.

It should return rows 3,4 and 5 because "file3" version1 is the latest version of file3.

我知道我需要在 SQL 中使用MAX"函数,但是我被GROUP BY"关键字抛弃了.我不是很熟悉如何使用它.

I know I need to use "MAX" function in SQL, however I'm getting throw off with the "GROUP BY" keyword. I'm not very familiar with how to use it.

感谢所有/任何建议!

我们使用的是 Oracle 11g.

We are using Oracle 11g.

推荐答案

确实,使用子查询获取MAX版本,按TITLE分组,然后加入结果与您的表获得ID:

Indeed, use a subquery to obtain the MAX version, grouped by TITLE, and then join the result of it with your table to obtain the ID:

SELECT t.*
FROM tbl t INNER JOIN 
     (SELECT title, MAX(version) version
      FROM tbl
      GROUP BY title
     ) max_t ON (t.version = max_t.version AND t.title = max_t.title);

演示.

这篇关于如何仅选择 SQL 中具有不同版本的文档列表的最大版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆