Expression not in aggregate or GROUP BY columns Exception - java

I have a table in MS-Access database named ItemRates which contains columns ItemID, ItemName, TotalFeet, RatePerItem, TotalRate and this database is connected with my java application.
When i run the following query
String sql = "SELECT SUM(TotalRate) AS ItemRateSum, TotalFeet FROM ItemRates";
I get the following exception
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.7 expression not in aggregate or
GROUP BY columns: PUBLIC.ITEMRATES.TOTALFEET
I have seen other questions related to this exception on StackOverflow and one accepted answer suggested to add GroupBy clause at the end of the query. I added a GroupBy clause
String sql = "SELECT SUM(TotalRate) AS ItemRateSum, TotalFeet FROM
ItemRates GROUPBY ItemName";
and i got almost same exception (there's a slight difference between two exceptions at the end after the colon)
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.7 expression not in aggregate or
GROUP BY columns: GROUPBY.TOTALFEET
What am i doing wrong here ?

The correct syntax is:
SELECT SUM(TotalRate) AS ItemRateSum, TotalFeet
FROM ItemRates
GROUP BY TotalFeet;
That is, TotalFeet is not an argument to an aggregation function, so it needs to be in the GROUP BY.

All columns which are selected and are not part of the aggregate functions have to be included in the group by clause

Related

jOOQ JSON query results in ORA-00979

I'm trying to execute this query to an Oracle 19c database:
Field<JSON> employee = DSL.field("employee", JSON.class);
Table<Record1<JSON>> employees = dsl
.select(jsonObject(jsonEntry("id", EMPLOYEE.ID), jsonEntry("name", EMPLOYEE.NAME), jsonEntry("phones",
jsonArrayAgg(
jsonObject(jsonEntry("number", PHONE.PHONENUMBER), jsonEntry("type", PHONE.TYPE)))
)).as(employee))
.from(EMPLOYEE)
.join(PHONE).on(PHONE.EMPLOYEE_ID.eq(EMPLOYEE.ID))
.groupBy(EMPLOYEE.ID)
.asTable();
String json = dsl
.select(jsonArrayAgg(employees.field(employee)))
.from(employees)
.fetchOneInto(String.class);
But I get
org.springframework.jdbc.BadSqlGrammarException: jOOQ; bad SQL grammar
[select json_arrayagg("alias_113372058".employee) from
(select json_object(key ? value "EMPLOYEE"."ID", key ? value "EMPLOYEE"."NAME", key ? value json_arrayagg(json_object(key ? value "PHONE"."PHONENUMBER", key ? value "PHONE"."TYPE"))) employee from "EMPLOYEE" join "PHONE" on "PHONE"."EMPLOYEE_ID" = "EMPLOYEE"."ID" group by "EMPLOYEE"."ID") "alias_113372058"];
nested exception is java.sql.SQLSyntaxErrorException: ORA-00979: Kein GROUP BY-Ausdruck
Does jOOQs JSON feature not work with Oracle?
This isn't related to your JSON usage. The same thing would have happened if you removed all of it and wrote this query instead:
dsl.select(EMPLOYEE.ID, EMPLOYEE.NAME)
.from(EMPLOYEE)
.join(PHONE).on(PHONE.EMPLOYEE_ID.eq(EMPLOYEE.ID))
.groupBy(EMPLOYEE.ID);
Your query would work in MySQL, PostgreSQL or standard SQL, where you can still project all functionally dependent columns after grouping by a primary key column. But in Oracle, this doesn't work. So, you have to add EMPLOYEE.NAME to your GROUP BY clause.
There's a feature request to transform your SQL accordingly, but jOOQ 3.14 does not support this yet: https://github.com/jOOQ/jOOQ/issues/4725
Note that JSON_ARRAYAGG() aggregates empty sets into NULL, not into an empty []. If that's a problem, use COALESCE()

SQL error an expression of non-boolean type specified in a context where a condition is expected, near 'AND'

I have the below sql
SELECT * FROM TABLE WHERE COLUMN LIKE CONCAT('%','CMP1','%') OR COLUMN LIKE
CONCAT('%','CMP2','%')
I am replacing this programatically
#Query(value = "SELECT * FROM TABLE WHERE ?1", nativeQuery = true)
List<Items> getAllItems(String param);
I had to append these OR conditions based on the user inputs so the conditions varies hence I used it as a combined OR statements.
How do I resolve this error?
Thanks in advance
Well, let's say I call getAllItems("Hello"). That means you end up trying to run SQL: "SELECT * FROM TABLE WHERE 'Hello'" which is invalid SQL for the exact reason stated: 'Hello' isn't a boolean. You can't put SQLese in that string (you can't call getAllItems("column like CONCAT('%', 'CMP1', '%')") - the point of these queries is that the SQL gets hardcoded and the dynamic data (the string param) is escaped.
You'd have to find a way to write this as a single SQL statement, or, don't use #Query.

How to avoid duplicating a function call in this JPA/JPQL query?

I have the following JPA query that truncates dates to a full hour and counts them:
SELECT a.alertconfiguration.id.id,
date_trunc('hour', a.date) AS fromDate,
count(*) AS count
FROM alert a
GROUP BY a.alertconfiguration.id.id,
a.alertlevel,
date_trunc('hour', a.date)
I'm running this in a Spring Boot application using Hibernate. It works fine. But I don't want to duplicate the function call to date_trunc.
I have tried referring to fromDate in the GROUP BY clause but then I get an exception org.postgresql.util.PSQLException: ERROR: column "fromdate" does not exist
http://hibernate.atlassian.net/browse/HHH-9301 also states it is not possible to refer to aliases in the group by clause.
How could I rewrite my query without the duplicate function call?
Can you give a try using 2 instead of date_trunc('hour', a.date) in group by clause, as fromdate is 2nd column
Hibernate does not work with alias in group by or any aggregate functions. And as you will see in your sql query generated, the alias is different than that you have assigned.

Hibernate GROUP BY invalid for Oracle

I created an Hibernate query like this:
select new ProjectForUser
(p.projectId, p.name, p.description, p.client, p.startDate, p.endDate,
p.liveDate, p.projectState, p.overallRagStatus, p.scopeRagStatus, p.flt,
up.projectManager)
from UserProjectAssociation up left join up.project p
where up.user.id = :userId and up.project.projectState != 'ARCHIVED'
group by p.projectId
to retrieve projects for user. Projects are stored in one table, users in the other and UserProjectAssociation is a joining table with additional attribute - projectManager.
The whole query works fine for H2 database, but on oracle I get this error:
ORA-00979: not a GROUP BY expression
What is a correct way to use GROUP BY for Oracle?
Thanks!
The Problem. ORA-00979 occurs when the GROUP BY clause does not contain all the expressions in the SELECT clause. Any SELECT expression that is not included in the GROUP function must be listed in the GROUP BY clause. These are AVG, COUNT, MAX, MIN, SUM, STDDEV, and VARIANCE.
see: https://www.tekstream.com/resources/ora-00979-not-a-group-by-expression/

java.lang.String cannot be cast HQL

Updated
Error says:
ava.lang.String cannot be cast to com.test.test.classes.TblTaxType
what is happening is when I add the tag select distinct taxtcode error is appearing. But when I removed the select tag like FROM tblTaxType tbl_tax_type WHERE bfnsCode = ? everything is fine. What is the cause? this is my code:
String hql = "SELECT DISTINCT TAXT_CODE FROM tbl_tax_type WHERE BFNS_CODE = ?";
try {
setSession(HibernateUtil.getSession());
#SuppressWarnings("unchecked")
List <TblTaxType> resultList = getSession().createSQLQuery(hql)
.setString(0, bfnsCode)
.list();
Your entity is probably named TblTaxType, not tblTaxType. Case matters.
Side note: don't name sql an HQL query. SQL and HQL are different languages.
Solved it using GROUP BY instead by using DISTINCT.
String hql = "FROM TblTaxType tbl_tax_type WHERE bfnsCode = ? GROUP BY taxtCode";
Your query returns TAXT_CODE, this field is a property of your TblTaxType entity, so you can't cast one property (string) in your main entity. This is the reason of your error.
If you need complete entity you must change your query but DISTINCT is not useful in this case because if you extract complete entity, there's ID field (different for each row). If you want a first element, you can add in your query ORDER BY clause with LIMIT 1 (is MySql).
A solution with GROUP BY works only if you use MySql as DBMS because if you have Sql Server the correct behaviour of field list / group by is: a field in field list must be in GROUP BY cluse or must be in aggregate function.

Categories