JPASQL查询,以获取给定输入名称的最大列数



我是Spring、Hibernate的新手,遇到了一个问题。我使用的是oracle数据库,我有一个这样的表。

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

我想";为给定名称和天气的每个产品获取最大街道;。

预期输出

输入-

姓名=约翰,天气=晴朗

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

名称=鸽子,天气=冬季

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

产品苹果被忽视,因为天气不是冬天。

我正在JPA中尝试这个查询,但它并没有给出想要的结果。

@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);

更新1:

我得到了结果,但不是选择最大街道。

有人能帮帮我吗?

如果我正确理解了这个问题,那么最好使用GROUP BY查询。

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

您可以采用这种方法,它通过子句使用组:

@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);

我运行了这些快速测试,结果与您的预期输出相匹配:

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

最新更新