从许多表中选择count(*)

时间:2013-02-18 08:32:10

标签: java mysql sql hibernate

亲爱的朋友们,我要求从一张桌子上获得不同标准的计数(*)。我正在使用带有spring的hibernate。我正在使用下面的查询。

"select  " +
            "(select count(*)  from enquiry  where business_id="+busid+")  AS allEnqCount,"+
    "(select count(*)  from enquiry where status='"+Constants.ENQ_FALLOWUP+"' and us.business_id="+busid+")  AS followupCount," +
    "(select count(*)  from enquiry where status='"+Constants.ENQ_SITE_VISIT+"'and us.business_id="+busid+")  AS siteVisitCount ," +
    "(select count(*)  from enquiry where status='"+Constants.ENQ_CUST_VISIT+"'and us.business_id="+busid+")  AS customerVisitCount," +
    "(select count(*)  from enquiry where status='"+Constants.ENQ_OFFICE_VISIT+"'and us.business_id="+busid+")  AS officevisitCount,"+
    "(select count(*)  from enquiry where status='"+Constants.ENQ_PENDING+"'and us.business_id="+busid+")  AS pending";

但它耗费了相当多的时间。你能告诉我有没有办法用最短的时间和一个选择条款来做到这一点。

提前致谢。

2 个答案:

答案 0 :(得分:2)

使用CASE

SELECT  SUM(CASE WHEN business_id = 'busid' THEN 1 END) allEnqCount,
        SUM(CASE WHEN status = 'ENQ_FALLOWUP' AND us.business_id = 'busid' THEN 1 END) followupCount,
        SUM(CASE WHEN status = 'ENQ_SITE_VISIT' AND us.business_id = 'busid' THEN 1 END) siteVisitCount,
        SUM(CASE WHEN status = 'ENQ_CUST_VISIT' AND us.business_id = 'busid' THEN 1 END) customerVisitCount,
        SUM(CASE WHEN status = 'ENQ_OFFICE_VISIT' AND us.business_id = 'busid' THEN 1 END) officevisitCount,
        SUM(CASE WHEN status = 'ENQ_PENDING' AND us.business_id = 'busid' THEN 1 END) pending
FROM    enquiry

只需更改满足您需求的值即可。

答案 1 :(得分:1)

使用group by

类似的东西:

select 
      status,
      count(*) 
from enquiry 
where business_id = @busid 
group by status