Query to get record of most recent date - java

I want to fetch the record from DB on basis of most recent date (latest date).
I have written one query down below which is not working and showing error :
11:55:05 select firstName,lastName from mb_orderhistory where
eventType="PROPOSED_ITEM_EDIT" and orderId=80822 and
MAX(updatedDate) GROUP BY orderId Error Code: 1111. Invalid use of
group function 0.015 sec
This is the query which i have written.
select firstName,lastName from mb_orderhistory where eventType="PROPOSED_ITEM_EDIT" and
orderId=80822 and MAX(updatedDate) GROUP BY orderId;

You can't use an aggregate (aka group) function — like MAX — in a WHERE clause. That's because the WHERE clause is evaluated against every possible row, whereas the aggregate function's value is only defined after you've seen all of the matching rows.
See MySQL's docs on SELECT syntax, and specifically:
In the WHERE expression, you can use any of the functions and operators that MySQL supports, except for aggregate (summary) functions.
Instead, you should just order by the updateDate (in descending order, such that the first row that's outputted is the greatest), and use LIMIT to get only one row:
SELECT ... WHERE orderId=80822 ... ORDER BY updatedDate DESC LIMIT 1
(A GROUP BY on a column doesn't make much sense if you also have an equality predicate on that column (orderId=80822). The predicate means that you will only have one group, and you'll know its value: in this case, 80822. The whole purpose of a GROUP BY is to identify groups; if you already know the group, you don't need it.)

In SQL Server, you can use order by like select top 1 firstname,lastname from <table_name> where <condition> order by updateddate desc

You could try:
select
firstName
,lastName
from mb_orderhistory
where eventType = "PROPOSED_ITEM_EDIT"
and orderId = 80822
and updateDate = (select max(updateDate) from mb_orderhistory where eventType = "PROPOSED_ITEM_EDIT" and orderId = 80822)

Select firstName,lastName
From mb_orderhistory
where eventType="PROPOSED_ITEM_EDIT"
and orderId=80822
and updatedDate = (SELECT MAX(updatedDate) FROM mb_orderhistory)
GROUP BY orderId;
This might be helpful to you! Tx.

Related

HQL : The column must appear in GROUP BY or in Select

I've this query with WrappedBean :
buffer.append("SELECT new myPackage.WrappedBean(E.debitant.id, E.dateCalcul, E.verse, E.incidenceReprise, E.soldeSoumission) ");
buffer.append("FROM " + getEntityClassName() + " E ");
buffer.append("LEFT JOIN E.debitant DT ");
buffer.append("WHERE E.debitant.id = :idDebitant ");
buffer.append("AND YEAR(E.dateCalcul) = :year ");
buffer.append("GROUP BY E.debitant.id");
hqlQuery = session.createQuery(buffer.toString());
hqlQuery.setInteger("idDebitant", idDebitant);
hqlQuery.setInteger("year", year);
I've created WrappedBean for returning somme columns and for using Group BY.
When i try to execute it, i obtain this error :
org.postgresql.util.PSQLException: ERREUR: The column « complement0_.date_calcul » must appear in GROUP BY clause or must be used in Select (i translate the error from french)
My POSTGRES query doesnt contain date_calcul in Group BY.
Another problem, in my query i've also this :
SUM(CASE WHEN YEAR(dateCalcul)=#PECAnnee AND verse>0 THEN verse ELSE 0 END)
I know in HQL, we cant do case when in select, for this reason, i dont add SUM to column verse
What i've forgot ?
My POSTGRES query doesnt contain date_calcul in Group BY
That's the problem and what Postgres is complaining about. Why isn't it in the SQL query? Because it isn't in the HQL query. Any column that is selected without the use of some aggregate method like sum(), min(), max() etc. needs to be part of the GROUP BY clause since otherwise the DB doesn't know how to handle multiple values/conflicts.
As an example, what value of E.dateCalcul should be passed to WrappedBean if there are multiple debitors (debitants) (which is most probably the case since otherwise there wouldn't be any need for the GROUP BY clause)?
So to fix this either use
GROUP BY E.debitant.id, E.dateCalcul, E.verse, E.incidenceReprise, E.soldeSoumission
or use aggregate functions, e.g.
WrappedBean(E.debitant.id, max(E.dateCalcul), min(E.verse), max(E.incidenceReprise), sum(E.soldeSoumission))

Spring data JPA - The encapsulated expression is not a valid expressio

While running the below query to get the latest message with the latest data using the createdOn column
i get the below error
select count(m) from MessageWorkFlowStatus mwfs1 where mwfs1.createdOn =(select max(createdOn) from MessageWorkFlowStatus mwfs2 where mwfs1.status= 'NEW' or mwfs1.status='IN PROGRESS')
The encapsulated expression is not a valid expression
Please let me know if i can run Query this way
First of all, count(m) is not correct. It should either be count(*) or count(mwfs1). Secondly, in your inner query, you are using status column from the outer query table (mswfs1) which is logically wrong. It should instead be mwfs2.status = 'NEW' or mwfs2.status = 'IN PROGRESS'.
I think your query should be:
select count(mwfs1)
from MessageWorkFlowStatus mwfs1
where mwfs1.createdOn = (
select max(createdOn)
from MessageWorkFlowStatus mwfs2
where mwfs2.status= 'NEW' or mwfs2.status='IN PROGRESS')

Order by, group by, first result in HQL (convert from Oracle SQL)

How would represent the following Oracle SQL in Hibernate HQL.
select table_num
, room_id
, min(event_type) keep(dense_rank first order by changed_on desc)
from room_history
group by table_num, room_id;
The idea behind the query is to order the table "room_history" by "changed_on" datetime column and then group it by "table_num" and "room_id" pairs whilest keeping the first "event_type" for each group. The mentioned query works for Oracle but I have trouble converting it into HQL.
Purpose is to get the latest "event_type" for "table_num" and "room_id" pair.
It seems this is not achievable
I ended up converting the following SQL query instead. It is not perfect but it does the job for my purposes.
select table_num, event_type et from room_history where id in (select max(id) from privacy_history group by msisdn);
I was able to do this assumptions since when for this table always a.id > b.id then also a.changed_on> b.changed_on.

extract column names from sql query after where clause

I've a requirement where I need to pull out data from database.
The query is-
SELECT e.Data AS EntityBlob, f.Data AS FpmlBlob
FROM [Trades.InventoryRecord] ir, EntityBlob e, FpmlBlob f
WHERE %s AND uid = e.uid AND uid = f.uid
Here %s is the predicate after where clause which user will input from an html form.
User input will be in this form :
1. TradeDate = '2013-04-05' AND IsLatest = 'TRUE'
2. StreamId= 'IA0015'
3. The query may have IN clause also
Now when this query is rendered I get exception ambigous column streamId or ambigous column IsLatest, as these columns exists in more than one table with same name. So to remove this ambiguity I need to modify the query as - ir.IsLatest or ir.StreamId
To do so by java code, I need to first parse the predicate after where clause, extract column names and insert table name alias- 'ir' before each column name so that the query becomes -
SELECT e.Data AS EntityBlob, f.Data AS FpmlBlob
FROM [Trades.InventoryRecord] ir, EntityBlob e, FpmlBlob f
WHERE ir.TradeDate = '2013-04-05' AND ir.IsLatest = 'TRUE' AND uid = e.uid AND uid = f.uid
what is the best way to parse this predicate, or if there is any other way I can achieve the same result?
My answer to this question is to not parse the user input - there is far too much that can go wrong. It would be a lot better to have a UI with drop downs and buttons for selecting equality, inequality, ranges, in statements, etc. It may seem like more work, but protecting yourself from a SQL injection attack is even more. And even if you are not concerned about malicious SQL injection, then the user still has to get every thing exactly right, or the statement fails.

getresultlist - query ok but data duplicate in List

I have a problem with getResultList().
My query is OK when it's executed and return 700 results.
In the return List, I had 700 results but the list contains duplicate data.
So I do not have all results.
public List<EscaleCatalogueKaravel> obtenirListeEscaleKaravelSelonMarche(Integer refMarche, Integer refLangue) {
List<EscaleCatalogueKaravel> listeEscales = entityManager.createQuery("select distinct p from EscaleCatalogueKaravel p " +
"where p.refMarche=:refMarche and p.refLangue=:refLangue group by idEscale ")
.setParameter("refMarche", refMarche)
.setParameter("refLangue", refLangue)
.getResultList();
if (listeEscales == null || listeEscales.size() == 0) {
return null;
}
return listeEscales;
}
Have you got an idea ?
You're using MySQL, right? Oracle would not execute the query but throw an error instead.
For correct usage of the group by clause you're only allowed to select that rows (or expressions) which are also mentioned in the group by clause. If you select a row which is not in the group by clause, this row might have different values for the members of one group. Which of these values the database should return? MySQL arbitrarily returns one of the possible values, but that is not correct.
In your query you either only do select distinct idEscale from ... or you group by all necessary columns and only select that ones or you drop your group by clause. By the way, distinct also can be used without group by, and distinct only should be used if really necessary because it makes the query slow.

Categories

Resources