1

我是 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:

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

有人可以帮帮我吗?

4

2 回答 2

0

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

 select name, weather, product, max(street)
 from Result r1
 where r1.name='John' and r1.weather='sunny'
 group by name, weather, product
于 2021-06-08T19:39:57.487 回答
0

您可以采用这种方法,它使用group by子句:

@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"));
于 2021-06-09T03:59:18.303 回答