有没有一种方法可以使用 "GREATEST(field1, field2)" SELECT,其中 field1 和 field2 是同一个 select 中的总和?

Is there a way to SELECT using "GREATEST(field1, field2)" where field1 and field2 are aggregate sums in the same select?

我有一个 java 应用调用一个用 HQL 编写的查询,调用 postgres。问题是我希望能够聚合(求和)两个字段,然后投影这些聚合的 "greatest"。有关 psql "greatest"

的文档,请参阅 https://www.postgresql.org/docs/8.4/functions-conditional.html

这可能吗?

我认为您可以通过将最大投影作为内部 select 的输出来执行所谓的 "nested aggregate" 查询?但是如果可以不嵌套这样写就更好了

select u.id, sum(foo.stat1) as stat1Sum, sum(foo.stat2) as stat2Sum, greatest(stat1Sum, stat2Sum)
from u, foo
where u.id = foo.uid
group by id

运行 我的查询结果出现以下错误:

Caused by: java.lang.IllegalStateException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode 
 \-[METHOD_CALL] MethodNode: '('
    +-[METHOD_NAME] IdentNode: 'GREATEST' {originalText=GREATEST}
    \-[EXPR_LIST] SqlNode: 'exprList'
       +-[IDENT] IdentNode: 'archiveBytesTotal' {originalText=archiveBytesTotal}
       \-[IDENT] IdentNode: 'selectedBytesTotal' {originalText=selectedBytesTotal}

我不认为我在映射对象上犯了任何错误,我认为问题在于 hibernate 无法派生出我用于总和聚合的别名类型。

感谢阅读!

HQL 支持的聚合函数是:

avg(...), sum(...), min(...), max(...)

count(*)

count(...), count(distinct ...), count(all...)

https://docs.jboss.org/hibernate/core/3.3/reference/en-US/html/queryhql.html

如果是重写查询的选项,您可以尝试FluentJPA,它支持您需要的功能。