简体   繁体   中英

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:

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. So I need some solution which is having functions supported by JPA 2.0. My database is Oracle 11g and JDK version is 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM