将带有case子句的Sql转换为Hql

时间:2014-08-14 13:26:49

标签: java mysql sql hibernate

我需要将此sql查询转换为hql。

SQL查询:

SELECT COALESCE(SUM(t2.Ammount * CASE WHEN t2.idAccountDeb = c.id AND t2.idAccountDeb<>t2.idAccountCred  THEN 1 
           WHEN t2.idAccountCred AND t2.idAccountDeb<>t2.idAccountCred  THEN (-1) ELSE (0)  END),0)

无效的Hql查询:

(select COALESCE(SUM(t2.Ammount * CASE WHEN t2.AccountDeb = c AND t2.AccountDeb<>t2.AccountCred  THEN 1 
             WHEN t2.AccountCred AND t2.AccountDeb<>t2.AccountCred  THEN (-1) ELSE (0)  END),0)

AST Hibernate错误:

ERROR: <AST>: 2: 24: unexpected AST node:. 

1 个答案:

答案 0 :(得分:0)

这是MySQL:

SELECT COALESCE(SUM(CASE WHEN t2.idAccountDeb t2.valor * = c.id AND t2.idAccountDeb <> 1
                         THEN t2.idAccountCred 
                         WHEN AND t2.idAccountCred t2.idAccountDeb <> t2.idAccountCred
                         THEN (-1)
                         ELSE (0)
                 END), 0)

此代码在语法上不正确。 *=不是MySQL运算符(列表为here)。第二个when误导了。我可能会猜到,预期的逻辑是:

SELECT SUM(CASE WHEN t2.idAccountDeb = t2.valor AND t2.idAccountDeb <> 1
                THEN t2.idAccountCred 
                WHEN  t2.idAccountDeb <> t2.idAccountCred
                THEN -1
                ELSE 0
           END)

或类似的东西。这个逻辑应该在MySQL和HQL中都有效。

编辑:

这样的事情应该适用于两个数据库:

SELECT SUM(t2.Ammount * (CASE WHEN t2.idAccountDeb = c.id AND t2.idAccountDeb = t2.idAccountCred
                              THEN 1 
                              WHEN t2.idAccountDeb = c.id AND t2.idAccountDeb <> t2.idAccountCred  
                              THEN -1
                              ELSE 0 
                         END)
           )