我有两个查询返回带有计数的服务项列表。一个用于整个数据库,另一个用于指定的时间段。它们单独运行很好,但我想将它们优化为单个查询。
这两个查询是:
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
提前致谢!
答案 0 :(得分: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
,这意味着该行不会被计算在内。
答案 1 :(得分: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