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

后端 未结 1 864
忘了有多久
忘了有多久 2021-01-06 11:39

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

With regular SQL, I could do this:

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

1条回答
  •  -上瘾入骨i
    2021-01-06 12:04

    The CriteriaBuilder interface provides the following arithmetic functions:

    • addition: sum(a, b)
    • substraction: diff(a, b)
    • multiplication: prod(a, b)
    • division: quot(a, b)

    where a b parameters can be an expression and/or literal.

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

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery q = cb.createQuery(Number.class);
    Root t = q.from(T.class);
    
    // build SUM(A * (100.0 - B) / 100.0) expression
    Expression diff = cb.diff(100.0, t.get("B"));
    Expression prod = cb.prod(t.get("A"), diff);
    Expression quot = cb.quot(prod, 100.0);
    Expression 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.get("A"), cb.diff(100.0, t.get("B"))), 100.0)).alias("D"));
    

    I hope it clarifies your doubts.

    0 讨论(0)
提交回复
热议问题