简体   繁体   中英

JPA SQL Query to fetch maximum column for given input Name

I am new to Spring, Hibernate and stuck on a problem. I am using oracle DB and I have a table like this.

Name   street    weather     product
John      2       sunny       google
John      1       sunny       apple
John      2       sunny       samsung
John      1       winter       google
John      1       spring       apple
John      3       sunny       samsung
Dove      1       winter       google
Dove      1       spring       apple
Dove      1       sunny       samsung
Dove      3       winter       google
Dove      1       spring       apple
Dove      2       winter       samsung

I want to "Fetch the maximum street for each product for the given Name and weather".

Expected Output

input -

Name=John, weather=sunny

Name   street    weather     product
John      2       sunny       google
John      1       sunny       apple
John      3       sunny       samsung

Name=Dove, weather=winter

Name   street    weather     product
Dove      3       winter       google
Dove      2       winter       samsung

product apple is ignored because weather is not winter.

I am Trying this Query in JPA, but it is not giving desired result.

@Query("select r1 from Result r1 left join Result r2 on (r1.name = r2.name "
      + "and r1.product=r2.product and r1.street>r2.street where r1.name=?1 and r1.weather=?2")
  List<Result> findResults(String name,String weather);

UPDATE 1:

I am getting the result but it is not selecting the maximum street.

Can someone please help me?

If I understand the problem correctly, this is probably best done with a GROUP BY query.

 select name, weather, product, max(street)
 from Result r1
 where r1.name='John' and r1.weather='sunny'
 group by name, weather, product

You could take this approach, which uses a group by clause:

@Query("SELECT " +
        "    new Result(r.name, max(r.street), r.weather, r.product) " +
        "FROM " +
        "    Result r " +
        "WHERE " +
        "    r.name = ?1 and r.weather = ?2 " +
        "GROUP BY " +
        "    r.name, r.weather, r.product")
List<Result> findResults(String name, String weather);

I ran these quick tests and the results match your expected output:

System.out.println(repository.findResults("John", "sunny"));
System.out.println(repository.findResults("Dove", "winter"));

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