首页 > 解决方案 > JPA SQL 查询以获取给定输入名称的最大列

问题描述

我是 Spring、Hibernate 的新手,遇到了一个问题。我正在使用 oracle DB,我有一张这样的表。

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:

我得到了结果,但它没有选择最大街道。

有人可以帮帮我吗?

标签: javasqlspring-boothibernatejpa

解决方案


如果我正确理解了问题,这可能最好使用 GROUP BY 查询来完成。

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

推荐阅读