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))
Related
I have tried using below query
#Query(value = "select E.SRC,E.TRGT,E.EVNT_STTS,E.ADDL_ATTR from EVNT.EVNT_LOG E where E.EVNT_ID=:eventId and E.ADDL_ATTR IS NULL" , nativeQuery = true)
List<AggregationLog> findByEventIdAndTargetAndAdditionalAttributeWithNULL(#Param("eventId") Long eventId);
in above query I am getting invalid column name.
Please guide me to select a row with eventID and addl_attr as null.
Well... invalid column means oracle cannot resolve the column name in the query. That usually means 1 of 2 things:
A Typo
The columns were created with case sensitivity. Whoever created the table surrounded the column names with double quotes and put column names in something other than all caps. Do a "DESCRIBE <table_name>" in sqlplus, sqldeveloper or any other client and check if the column names are all upper case. If they're not, you will need to enclose them in double quotes in your query with the name matching exactly what you see.
I have this native query:
"SELECT DATE_FORMAT(createdDate, \"%Y-%M\") AS open_month, :" + filter
+ " AS filterName, COUNT(id) AS counts from cases group by open_month, :"
+ filter + " ;"
And then use setResultTransformer and Transformers.aliasToBean to convert to my DTO.
In database, Feb has two records using the query that Hibernate print out
SELECT
DATE_FORMAT(createdDate, "%Y-%M") AS open_month,
? AS filterName,
COUNT(id) AS counts
FROM
cases
GROUP BY
open_month,
?;
But when I get query.list(), 2017-Feb has only one record and the counts is 5, meaning that two records are merged.
Does anyone know why is this and how to return the exact result?
It seems like the same parameter will break the query like this: Using hibernate named parameter twice
If I use different parameter names then it works fine
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.
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.
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.