带有大小写的HQL,总和为max

时间:2019-02-05 13:39:38

标签: java hibernate jpa hql

我有一个 query 出现问题,我相信会出现问题是因为它不允许使用max函数中的max函数,是吗?对吗?

我该如何解决?我需要添加除最后一个row以外的所有值。

查询:

"SELECT new project.domain.vo.MediaPagVo(" +
                    "a.nomeUsuario, " +
                    "a.cpfUsuario, " +
                    "a.cnpjUnidadeUsuario,        " +
                    "a.nomeUnidadeUsuario,        " +
                    "a.codigoGrupoUsuario,        " +
                    "a.grupo.id AS idGrupo,         " +
                    "CASE " +
                        "WHEN MAX(a.pre) - MIN(a.pre) > 0 " +
                        "THEN ((MAX(a.pre) - MIN(a.pre)) / SUM(CASE WHEN max(a.dtRequisicao) > a.dtRequisicao THEN a.valorTotal ELSE 0 END)) " +
                        "ELSE ((MAX(a.pos) - MIN(a.pos)) / SUM(CASE WHEN max(a.dtRequisicao) >= a.dtRequisicao THEN a.valorTotal ELSE 0 END)) " +
                    "END AS mediaConsumo, " +
                    "CASE " +
                        "WHEN MAX(a.pre) - MIN(a.pre) > 0 " +
                        "THEN " + Tipo.PRE.getValue() + " " +
                        "ELSE " + Tipo.POS.getValue() + " " +
                    "END AS tipoPag) " +
            "FROM " +
                    " Pagamento a " +
            "WHERE " +
                    "a.status = " + StatusPagamento.Concluido.getValue() + " AND " +
                    "a.dataRequisicao BETWEEN :inicio and :fim AND " +
                    "( :idGrupo IS NULL OR a.grupo.id = :idGrupo) " +
                   "GROUP BY " +
                    " a.nomeUsuario, a.cpfUsuario, a.cnpjUnidadeUsuario, a.nomeUnidadeUsuario, a.codigoGrupoUsuario, a.grupo.id, " +
            "HAVING (MAX(a.pos) - MIN(a.pos) > 0 OR MAX(a.pre) - MIN(a.pre) > 0) AND " +
                    "( :tipoConsumo IS NULL OR " +
                        ":tipoConsumo = " + Tipo.PRE.getValue() + " AND " +
                        "(MAX(a.pre) - MIN(a.pre) > 0) " +
                        "OR :tipoConsumo = " + Tipo.POS.getValue() + " AND " +
                        "(MAX(a.pos) - MIN(a.pos) > 0) ) ";

在我修改了本节并将case添加到sum内之后,错误开始发生:

"CASE WHEN MAX(a.pre) - MIN(a.pre) > 0 " +
                        "THEN ((MAX(a.pre) - MIN(a.pre)) / SUM(CASE WHEN max(a.dtRequisicao) > a.dtRequisicao THEN a.valorTotal ELSE 0 END)) " +
                        "ELSE ((MAX(a.pos) - MIN(a.pos)) / SUM(CASE WHEN max(a.dtRequisicao) >= a.dtRequisicao THEN a.valorTotal ELSE 0 END)) " +
                    "END AS mediaPag, " 

java返回的错误:

Could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

ORA-00937: not a single-group group function tips

我的目标是总计减去该期间的所有付款。不幸的是,我不能只移动过滤器,因为max (a.pre), max (a.pos)可能是最后一笔付款。有人有什么想法吗?

1 个答案:

答案 0 :(得分:0)

也许还值得询问如何重构此查询。性能有问题吗?我的意思是,如果不运行一个查询,而是运行几个较小的查询,那么系统将非常慢。

例如在单独的查询中获取MIN MAX(a.pre),在Java代码中进行SUM(CASE WHEN,并将这些值作为参数传递。

如果您决定重构,首先添加一些测试以查看具有特定值的旧查询的行为将是安全的。然后进行重构。最后,重新运行您添加的测试,以检查您没有添加任何错误。