[英]SQL + JPA : return rows with maximum value of single column
My DB Table data looks like:我的数据库表数据如下所示:
col1 col2 col3 col4 col5 col6
value null null blaDiff 0 x1
value null null blaDiff 0 x2
value null blabla null 1 x1
value null blabla null 1 x3
value bla null null 2 x1
value bla null null 2 x2
value otherBla null null 2 x3
I wish to fetch rows having maximum value of col5 but only those rows which satisfy filter criteria.I could make it work using query which looks like:我希望获取具有最大值 col5 的行,但只获取那些满足过滤条件的行。我可以使用如下所示的查询使其工作:
SELECT col1
,col5
,col6
FROM TABLE v
WHERE v.col1 = 'value'
AND (
v.col2 = 'bla'
OR v.col3 = 'blabla'
OR v.col4 = 'blaDiff'
)
AND v.col5 = (
SELECT MAX(v.col5)
FROM TABLE v1
WHERE v1.col1 = 'value'
AND (
v.col2 = 'bla'
OR v.col3 = 'blabla'
OR v.col4 = 'blaDiff'
)
);
Then my result looks like:然后我的结果看起来像:
col1 col2 col3 col4 col5 col6
value bla null null 2 x1
value bla null null 2 x2
What I would like to know is if there is any better and easy way to do this.我想知道的是是否有更好和更简单的方法来做到这一点。 Please note that, I have mentioned JPA in my subject because, afterwards I need to write this logic using JPA Criteria builder.
请注意,我在我的主题中提到了 JPA,因为之后我需要使用 JPA Criteria builder 编写此逻辑。 So I need some solution which is having functions supported by JPA 2.0.
所以我需要一些具有 JPA 2.0 支持的功能的解决方案。 My database is Oracle 11g and JDK version is 1.7.051.
我的数据库是 Oracle 11g,JDK 版本是 1.7.051。
I would be inclined to use window functions:我倾向于使用窗口函数:
SELECT col1, col5, col6
FROM (SELECT v.*,
MAX(col5) OVER (PARTITION BY col1) as max_col5
FROM TABLE v
WHERE v.col1 = 'value' AND
(v.col2 = 'bla' OR v.col3 = 'blabla' OR v.col4 = 'blaDiff')
) v
WHERE v.col5 = v.max_col5;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.