'Combining distinct, group by and order by in complicated HQL queries
Actually I have been trying to use group by , order by in HQL queries whole day yet no result has been found. I have researched a lot in different articles and stackoverflow's questions answers and gone through many of them and tried but none of the answers could answer in my scenario.
I am writing a query that basically should fetch unique values but has joining and more as shown in the code below in groovy syntax.
String query = "select o ${queryAndParams?.queryString}"
Here, queryAndParams?.queryString will be generated based on the options we pass as params which has no problem.
One of the queries from the log is
select o from RequestOffer o inner join o.request r
inner join r.event e inner join o.offerParts as rop
inner join o.statusLogs lg where lg.dateCreated between :fromDate
and :toDate and o.status = :approvedStatus and o.deletedDate is null and
r.removeFromAdminReport = false and e.removeFromAdminReport = false and
e.isTemplate is false and r.isTemplate is false group by o.id, e.fromDate order by
e.fromDate + age(min(rop.dateTimeFrom) , '1970-01-01 00:00') desc
This query is fine except it is giving duplicating and for some reasons I want to filter out explicitly in query level [while fetching from DB].
It would have been not that difficult but due to order by e.fromDate + age(min(rop.dateTimeFrom) , '1970-01-01 00:00')
I am not being able to properly implement.
I tried select distinct o from RequestOffer o .... and it doesn't work as select doesn't have e.fromDate + age(min(rop.dateTimeFrom)
Also when wrting elect distinct o, e.fromDate + age(min(rop.dateTimeFrom) from RequestOffer o .... also doesn't work as it is searching distinct for both.
I somehow noticed that pure PostgreSQL query in my console working and has syntax
select distinct on(o) o from request_offer o inner join request r on r.id = o.request_id
inner join event e on r.event_id = e.id
inner join request_offer_part rop on o.id = rop.offer_id
inner join request_offer_status_log lg on lg.offer_id = o.id where lg.date_created
between '2021-03-01' and '2022-03-07' and o.status = 'APPROVED'
and o.deleted_date is null and
r.remove_from_admin_report = false and e.remove_from_admin_report = false
and e.is_template is false and r.is_template is false
group by o.id, e.from_date order by o, e.from_date +
age(min(rop.date_time_from) ,'1970-
01-01 00:00') desc;
This seems to work fine but it isn't supported in HQL. I've been somehow stuck due to this and would appreciate any guidance or code snippets.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
