[英]SQL: Filter rows with max value
这是我的表结构:
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
...
我看过如何通过SQL中的另一列来选择具有MAX(列值),DISTINCT的行? ,但是会返回最新的唯一函数ID。
该查询必须与sqlite3兼容。
一种有效的方法通常是使用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)
上的索引。
这将查询重新表述为:“从表中获取其中相应文件没有较大版本的所有行。”
在SQLite 3.7.11或更高版本中,当您使用MAX时,保证其他值来自具有最大值的行:
SELECT File,
MAX(Version) AS Version,
Function
FROM MyTable
GROUP BY File
请注意,如果文件具有针对不同功能的整体最新版本,则它将为每个文件返回多行。 即,如果上面的示例中有另外一行(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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.