简体   繁体   English

JPQL select 查询,无法分组

[英]JPQL select query, unable to Group By

after hours I don't seem to find a way to achieve this, I have 2 entities:几个小时后,我似乎没有找到实现这一目标的方法,我有 2 个实体:

public class Price{
@Id
int id;

@Temporal(TemporalType.DATE)
private Date dtComu;

private String descCarb;

private Double price;

//bi-directional many-to-one association to Distributor
@ManyToOne
@JoinColumn(name="idImpiant")
private Distributor distributor;

AND

public class Distributor{

@Id
private int idImpiant;

private String province;

//bi-directional many-to-one association to Price
@OneToMany(mappedBy="distributor")
private List<Price> prices;

What I need to do seems pretty simple, for each distributor, get the latest price.我需要做的似乎很简单,为每个经销商,获取最新的价格。 What i thought was to get a list of Prices(each price with have a distributor), order by date and group by distributor.我的想法是获取价格清单(每个价格都有一个经销商),按日期订购,按经销商分组。 My query is:我的查询是:

SELECT e FROM Price e JOIN e.distributor d WHERE e.descCarb like '%Diesel%' group by e.distributor order by e.dtComu desc

The error i get is:我得到的错误是:

SELECT list is not in GROUP BY clause and contains nonaggregated column 'price0_.id' which is not functionally dependent on columns in GROUP BY clause SELECT 列表不在 GROUP BY 子句中,并且包含在功能上不依赖于 GROUP BY 子句中的列的非聚合列“price0_.id”

is there another way i haven't thought to achieve this?还有另一种我没想到的方法吗?

The error you see is stemming from that it is not clear which entity you want per distributor group.您看到的错误源于您不清楚每个分销商组需要哪个实体。 Here is one way to do this using HQL:这是使用 HQL 执行此操作的一种方法:

select e FROM Price e JOIN e.distributor d
where e.descCarb like '%Diesel%' and
      e.dtComu = (select max(ee.dtComu) from Price ee where ee.distributor = e.distributor)

This uses a correlated subquery to check that the matching Price entity is the latest one for each distributor.这使用相关子查询来检查匹配的Price实体是否是每个分销商的最新实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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