【问题标题】:Subtract or add values from sum depending on the another column value根据另一列值从总和中减去或添加值
【发布时间】:2019-04-12 18:46:32
【问题描述】:

我想根据另一个列值(类型)的条件来求和或减去值(数量)。在 vanilla sql 中会是这样的:

sum( if(`type` = 1, -1, 1) * `quantity` )

我如何使用querydsl 4 来实现这一点。这就是我目前所拥有的

collectionTransaction.quantity.sum()

我想不通的是实现其中的逻辑。

【问题讨论】:

  • 在 Sql 中,CASE 不是比 IF 更普通吗?无论如何,我会考虑在 QueryDsl 中使用对 Case 语句的支持

标签: java mysql spring-data-jpa querydsl


【解决方案1】:

根据@Joakim Danielson 的参考资料,我设法做到了。这就是我做对的方式:

new CaseBuilder() 
      .when(collectionTransaction.collectionType.eq(1))
      .then(collectionTransaction.quantity.sum())
      .otherwise(collectionTransaction.quantity.negate().sum()),

翻译成下面的sql语句:

case 
  when collection0_.collection_transaction_type=1 then sum(collection0_.quantity) 
  else sum(-collection0_.quantity) 
end as col_1_0_,

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    相关资源
    最近更新 更多