简体   繁体   中英

Query group by in h2 works but not in Oracle DB

i have a query like the following:

SELECT
  sum(field1) as t1.sum_f1,
  (select count(*) from table2) as count_t2,
  t1.f2
FROM 
  t1
GROUP BY 
  t1.f2

This query is getting executed by a javax.persistence.EntityManager java istance.
EntityManager runs the query in an Oracle DB.
I've written Mockito test, configured with H2 in memory database.

The problem is the following:
When the same query is getting executed by a Mockito test (that uses H2 as DB), it works fine.
When i run my java application (that uses OracleDB as DB) it gives me ERROR: ORA-00979.

I think it expects count_t2 to be in the group by field list but this is not permitted cause inner queries are processed after gruop by (so count_t2 is not visible at "group by - time") in SQL.

How can i solve it?
Thanks.

Move the calculation to the FROM clause:

SELECT SUM(field1) as t1.sum_f1, t2.count_t2, t1.f2
FROM t1 CROSS JOIN
     (SELECT COUNT(*) as count_t2 FROM  table2) t2
GROUP BY t1.f2, t2.count_t2;

Subqueries with aggregation queries can be tricky for query parsers.

I finally found the way to let it works.

SELECT
  sum(field1) as t1.sum_f1,
  count((select 1 from table2)) as count_t2,
  t1.f2
FROM 
  t1
GROUP BY 
  t1.f2  

In this way projection fields are "SUM, COUNT" and the aggregation field. This query works fine in both H2 and ORACLE DB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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