2

我有两个查询返回带有计数的服务项目列表。一个是针对整个数据库的,另一个是针对指定时间段的。它们单独工作得很好,但我想将它们优化为一个查询。

这两个查询是:

SELECT service_type, count(service_type) from qba_customers group by service_type order by count(service_type) desc

SELECT service_type, count(service_type) from qba_customers WHERE created_on BETWEEN '2013-01-01' AND '2013-06-30' group by service_type order by count(service_type) desc

我尝试了一些不成功的事情,以下是我最初认为可行的方法:

SELECT service_type, COUNT(service_type) AS full_count, (count(service_type) WHERE created_on BETWEEN '2013-01-01' AND '2013-06-30') AS period_count FROM qba_customers GROUP BY service_type ORDER BY service_type DESC

提前致谢!

4

2 回答 2

0

包括 在内的所有聚合函数COUNT只会包含一个不为 NULL 的值。要仅计算日期范围内的行数,请使用该CASE构造作为 count 参数。如果 CASE 返回一个值,则对其进行计数。如果它不返回值,则不计算在内:

SELECT
  service_type,
  COUNT(service_type) AS GrandTotal,
  COUNT(CASE WHEN created_on BETWEEN '2013-01-01' AND '2013-06-30' THEN 1 END) AS FirstHalf2013
FROM qba_customers
GROUP BY service_type
ORDER BY GrandTotal

对于FirstHalf2013列,如果created_on在目标范围内,则 CASE 返回一个非空值(我1在这里使用过,但它可以是任何非空值)。如果created_on不在目标范围内,则CASE返回NULL,这意味着该行不被计算在内。

于 2013-08-07T04:19:04.727 回答
0

尝试使用 case 语句:

SELECT service_type, 
       count(service_type) as full_count,
       sum(case when created_on between '2013-01-01' and '2013-06-30' then 1 else 0 end) as period_count 
  FROM qba_customers 
 GROUP by service_type
 ORDER by service_type desc
于 2013-08-07T04:22:22.070 回答