我正在研究Hibernate查询。此查询适用于MySQL,但在Oracle和postgreSQL中失败。
SELECT MIN(t.startTime) AS StartTime,
MAX(t.endTime) AS EndTime,
(SELECT SUM(t2.occurances) from table2 as t2)
from table1 as t1
我收到错误 -
ORA-00937:不是单组组功能
如何解决此问题?该表只返回一行。如果我通过在SELECT中添加一个额外的列来添加group by,它将返回多行。
答案 0 :(得分:2)
由于group by
的MySQL扩展,这适用于MySQL。不幸的是,编译器在查看聚合查询时,子查询不会被视为“常量”。所以,这只是group by
子句中的另一个表达式。
这是一种编写兼容所有三个数据库(但不适用于Hibernate)的查询的方法:
SELECT MIN(t.startTime) AS StartTime, MAX(t.endTime) AS EndTime, MAX(occurrences)
from table1 t1 cross join
(SELECT SUM(t2.occurrences) as occurrences from table2 t2) t2;
我应该补充一点,你也不能将子查询添加到group by
子句中,尽管以下内容适用于Oracle和Postgres:
SELECT MIN(t.startTime) AS StartTime, MAX(t.endTime) AS EndTime,
(SELECT SUM(t2.occurances) from table2 t2)
FROM table1 t1
GROUP BY 3;
编辑:
与标准SQL相比,HQL非常严格。以下是 close 两个你想要的,但它返回至少两行而不是1行:
select t.starttime, t.endtime, (SELECT SUM(t2.occurances) from table2 t2)
from table1 t
where t.starttime = (select min(starttime) from table1) or
t.endtime = (select max(endtime) from table1);
答案 1 :(得分:1)
试试这个:
with t1 as (
SELECT MIN(t.startTime) AS StartTime,
MAX(t.endTime) AS EndTime
from table1 as t1
), t2 as (
SELECT SUM(t2.occurances) occurances from table2 as t2
)
select t1.starttime, t1.endtime, t2.occurances
from t1, t2
答案 2 :(得分:1)
只需为第三列添加GROUP BY
:
SELECT MIN(t1.startTime) AS StartTime,
MAX(t1.endTime) AS EndTime,
(SELECT SUM(t2.occurances) FROM table2 t2) as occurances
FROM table1 t1
GROUP BY 3
此查询返回一行。
修改强>
或者,您可以使用其他聚合函数(例如MAX
),然后不需要GROUP BY
:
SELECT MIN(t1.startTime) AS StartTime,
MAX(t1.endTime) AS EndTime,
MAX( (SELECT SUM(t2.occurances) FROM table2 t2) ) as occurances
FROM table1 t1