Java 如何在某些单元格上使用自定义操作的 CriteriaQuery SUM?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21627704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:44:38  来源:igfitidea点击:

How to use CriteriaQuery SUM of custom operation on some cells?

javasqlexpressionaggregate-functionscriteria-api

提问by ioreskovic

Consider you have table T, with fields A and B.

假设您有表 T,其中包含字段 A 和 B。

With regular SQL, I could do this:

使用常规 SQL,我可以这样做:

SELECT SUM(A * (100.0 - B) / 100.0) AS D FROM T;

And I would get exactly what I expect.

我会得到我所期望的。

However, I'm not sure how to do it with CriteriaQuery.

但是,我不确定如何使用 CriteriaQuery 来做到这一点。

I know how to do sum over 1 field, but not how to do sum over some math expression over multiple fields in a row.

我知道如何对 1 个字段求和,但不知道如何对连续多个字段的某些数学表达式求和。

采纳答案by wypieprz

The CriteriaBuilderinterface provides the following arithmetic functions:

CriteriaBuilder接口提供以下算术函数:

  • addition: sum(a, b)
  • substraction: diff(a, b)
  • multiplication: prod(a, b)
  • division: quot(a, b)
  • 添加: sum(a, b)
  • 减法: diff(a, b)
  • 乘法: prod(a, b)
  • 分配: quot(a, b)

where abparameters can be an expression and/or literal.

其中ab参数可以是表达式和​​/或文字。

As for the query, here is an exampe written in a human readable form:

至于查询,这是一个以人类可读形式编写的示例:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Number> q = cb.createQuery(Number.class);
Root<T> t = q.from(T.class);

// build SUM(A * (100.0 - B) / 100.0) expression
Expression<Double> diff = cb.diff(100.0, t.<Double>get("B"));
Expression<Double> prod = cb.prod(t.<Double>get("A"), diff);
Expression<Number> quot = cb.quot(prod, 100.0);
Expression<Number> sum = cb.sum(quot);
q.select(sum.alias("D"));

System.out.println(em.createQuery(q).getSingleResult());

You can also build the query as an one-liner:

您还可以将查询构建为单行:

q.select(cb.sum(cb.quot(cb.prod(t.<Double>get("A"), cb.diff(100.0, t.<Double>get("B"))), 100.0)).alias("D"));

I hope it clarifies your doubts.

我希望它能澄清你的疑惑。