SUM中的“CASE WHEN”子句

时间:2014-06-24 14:19:04

标签: jpa jpql criteria-api case-when

我的表/实体如下所示:

*ID* | *Description* | *Error* | *batchId*
  1  | test 111      |    0    | 456
  2  | test 222      |    1    | 456
  3  | test 333      |    0    | 456
  4  | test xxx      |    1    | 458
  5  | test yyy      |    1    | 458

我试图以这种形式选择结果:

batchId | HowManyOK | HowManyErrors 
   456  |     2     |       1
   458  |     0     |       2

在JPQL中,我试过了:

SELECT 
   g, 
   SUM( CASE WHEN g.error = false THEN 1 ELSE 0 END ) AS ok, 
   SUM( CASE WHEN g.error = false THEN 1 ELSE 0 END ) AS ko  
FROM
   GoogleMerchantLog g 
GROUP BY g.batchId

但它没有编译!它声称错误"封装的表达式不是有效的表达式。"在SUM。

也许有一些建议要使用Criteria API来解决它?

没有解决方案? 我终于解决了映射本机查询:((

1 个答案:

答案 0 :(得分:1)

这是我刚刚写的代码:

@Query("SELECT new be.mteam.zoomit.persistence.vo.ZoomitValidation(Z.organization, " +
            "Z.documentType, " +
            "Z.language, " +
            "Z.recipientProfil, " +
            "Z.documentDate, " +
            "sum(case when(Z.status = be.mteam.zoomit.persistence.vo.ZoomitStatus.WAITVALIDATION) then 1 else 0 end), " +
            "sum(case when(Z.status = be.mteam.zoomit.persistence.vo.ZoomitStatus.WAITTOSEND " +
            "or Z.status = be.mteam.zoomit.persistence.vo.ZoomitStatus.POSTED " +
            "or Z.status = be.mteam.zoomit.persistence.vo.ZoomitStatus.CREATED " +
            "or Z.status = be.mteam.zoomit.persistence.vo.ZoomitStatus.SENDING) then 1 else 0 end), " +
            "sum(case when(Z.status = be.mteam.zoomit.persistence.vo.ZoomitStatus.SENT) then 1 else 0 end)) " +
        "from Zoomit as  Z " +
        "where Z.organization = :organization " +
            "and Z.status in (be.mteam.zoomit.persistence.vo.ZoomitStatus.WAITVALIDATION," +
            "be.mteam.zoomit.persistence.vo.ZoomitStatus.WAITTOSEND," +
            "be.mteam.zoomit.persistence.vo.ZoomitStatus.POSTED," +
            "be.mteam.zoomit.persistence.vo.ZoomitStatus.CREATED," +
            "be.mteam.zoomit.persistence.vo.ZoomitStatus.SENDING," +
            "be.mteam.zoomit.persistence.vo.ZoomitStatus.SENT) " +
        "group by Z.organization, Z.documentType, Z.language, Z.recipientProfil, Z.documentDate")
List<ZoomitValidation> getValidations(@Param("organization") String organization);

执行成功。

您的代码:

来自:

SELECT 
   g, 
   SUM( CASE WHEN g.error = false THEN 1 ELSE 0 END ) AS ok, 
   SUM( CASE WHEN g.error = false THEN 1 ELSE 0 END ) AS ko  
FROM
   GoogleMerchantLog g 
GROUP BY g.batchId

致:

SELECT 
   g.batchId, 
   SUM(CASE WHEN (g.error = false) THEN 1 ELSE 0 END) AS ok, 
   SUM(CASE WHEN (g.error = true) THEN 1 ELSE 0 END) AS ko  
FROM
   GoogleMerchantLog g 
GROUP BY g.batchId

马文:

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.2.5.RELEASE</version>

PS : 没有找到使用静态导入来缩短 ZoomitStatus 枚举的方法。