如何使用别名添加查询的count(id),count(name)

时间:2018-03-29 13:37:40

标签: java sql hibernate

我想添加从子查询中获取的计数并为其分配别名。有没有办法只使用提供的别名添加它们而不是使用

select 
   ( select count(*)... subquery1 ) as s1,  
   (subquery2 ) as s2,  (subquery3 ) as s3, 
   add ( (subquery1 ) + (subquery2) + (subquery3)) 
from tableName

在上面的查询中,如果我想添加它们的计数,我需要再次调用子查询。我们可以简单地使用像

这样的别名
select (subquery1 ) as s1,  
       (subquery2 ) as s2,
       (subquery3 ) as s3, 
       add (s1  + s2+ s3) 
from tableName

2 个答案:

答案 0 :(得分:0)

您可以使用嵌套查询

Select *,(s1 + s2 + s3) as add from
(select ( select count(*)... subquery1 ) as s1,  
        (subquery2 ) as s2,  
        (subquery3 ) as s3 
 from tableName) AS T1

答案 1 :(得分:0)

您可以使用课程以不同的方式进行演示。

public class MyResult {
    private Long s1;
    private Long s2;
    private Long s3;
    private Long total;

    public MyResult(Long s1, Long s2, Long s3){
       this.s1 = s1;
       this.s2 = s2;
       this.s3 = s3;
       this.total = s1+s2+s3;
    }
    // getter e setter
}

在JPQL的查询(或命名查询)中,您可以编写:

SELECT my.package.MyResult(
   (subquery1),
   (subquery2),
   (subquery3),
) 
FROM tableName

在代码中,您可以调用

List<MyResult> results = this.em.createQuery(...).getResultList();