来自计算字段/表达式的JPQL ORDER BY

时间:2012-08-05 03:55:27

标签: hibernate jpa sql-order-by expression jpql

这是JPA/JPQL: AS identifier disallowed in SELECT clause基本上的后续问题。

这是JPQL查询:

  SELECT NEW com.domain.project.view.StandingsStatLine(
      ro.id
    , cl.name
    , te.ordinalNbr + 1
    , pa.wasWithdrawn
    , SUM(CASE WHEN paf.wasWithdrawn = FALSE AND paa.wasWithdrawn = FALSE AND scf.finalScore IS NOT NULL THEN 1 ELSE 0 END)       // g = games
    , SUM(CASE WHEN paf.wasWithdrawn = FALSE AND paa.wasWithdrawn = FALSE AND scf.finalScore > sca.finalScore THEN 1 ELSE 0 END)  // w = wins
    , SUM(CASE WHEN paf.wasWithdrawn = FALSE AND paa.wasWithdrawn = FALSE AND scf.finalScore < sca.finalScore THEN 1 ELSE 0 END)  // l = losses
    , ...
    , <very complex multi-line expression> // nrp = normalized ranking points
    )
  FROM Club cl
    JOIN cl.teams te
    JOIN te.rosters ro
    JOIN ro.season se
    JOIN ro.participations pa
    JOIN pa.group gr
    JOIN gr.round rd
    JOIN rd.subCompetition sc
    JOIN sc.competition cn
    JOIN gr.games ga
    JOIN ga.scores scf
    JOIN ga.scores sca
    JOIN scf.roster rof
    JOIN sca.roster roa
    JOIN rof.participations paf
    JOIN roa.participations paa
  WHERE ...
  GROUP BY ...
  ORDER BY pa.wasWithdrawn, nrp DESC, w DESC, g DESC, cl.shorthand

这与上一个问题没有 ... AS ...表达式的声明相同。

对于有兴趣的人:

  1. nrp是“标准化排名点”。这是根据所玩游戏的最大可达到点数的简单百分比。背景是,一支有10场比赛的球队总得分(每场比赛获得1分)比仅参加6场比赛的球队要高得多。这是实际的排名指标。 w和g在代码中解释。
  2. scf和sca得分为和反对(在WHERE中过滤)
  3. 问:

    你如何ORDER BY在JPQL中计算这些属性?我经常这样做,但由于SELECT中的... AS ...似乎是无效的JPQL(Hibernate可以处理它们),你通常如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

找到它。另请参阅http://en.wikibooks.org/wiki/Java_Persistence/JPQL_BNF#New_in_JPA_2.0。请注意,那里的倒数第二示例。

select_item ::= select_expression [[AS] result_variable]

在选择中允许AS选项。

SELECT AVG(e.salary) AS s,
    e.address.city
FROM Employee e
GROUP BY e.address.city
ORDER BY s

我不知道构造函数表达式是否也支持它,但我认为没有理由不这样做。