Counting Null values in JPQL

╄→尐↘猪︶ㄣ 提交于 2019-12-13 22:22:57

问题


i want to count null values in JPQL but count (case when "column" is null then.. end) doesn't work it work only on MYSQL ,i don't want to use count(*) what is the solution ??

String jpql ="select c.commande.user.login ,count(CASE WHEN c.commande.commandeTms is Null THEN 1 else 0 END) AS count1   from Designation c GROUP BY c.commande.user.login";

here my database


回答1:


Here you go : I have used CriteriaBuilder to count them ... as a result, you get a List of Tuple containing the user login and count elements ... you may want to change names and "count cases" according to your needs :

public List<Tuple> test() {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
    Root<Designation> designation = cq.from(Designation.class);

    Join<Designation, Commande> commande = designation.join("commande");
    Join<Commande, User> user = commande.join("user");

    Expression expr = commande.get("commandeTms");

    cq.multiselect(user.get("login").alias("login"), 
            cb.sum(cb.<Long>selectCase().when(expr.isNotNull(), 1L).otherwise(0L)).alias("NotNull"),
            cb.sum(cb.<Long>selectCase().when(expr.isNull(), 1L).otherwise(0L)).alias("Null"));
    cq.groupBy(user.get("login"));

    Query query = entityManager.createQuery(cq);
    return query.getResultList();
}



回答2:


You can use SUM aggregate function for this case

String jpql ="SELECT c.commande.user.login, SUM(CASE WHEN c.commande.commandeTms IS NULL THEN 1 ELSE 0 END) AS count1 FROM Designation c GROUP BY c.commande.user.login";


来源:https://stackoverflow.com/questions/32376952/counting-null-values-in-jpql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!