3

亲爱的朋友们,我需要从一张具有不同标准的表中获取计数(*)。我正在使用带有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";

但它需要相当多的时间。你能告诉我有没有什么方法可以用最少的时间和一个单一的选择子句来做到这一点。

提前致谢。

4

2 回答 2

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

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

于 2013-02-18T08:37:39.240 回答
1

使用group by

就像是:

select 
      status,
      count(*) 
from enquiry 
where business_id = @busid 
group by status
于 2013-02-18T08:43:28.747 回答