聚合多个选择查询sql

时间:2016-11-21 14:54:25

标签: sql

所以我使用此查询来计算数据库中的身份验证错误数:

SELECT  (
SELECT COUNT(audit.server_response_code)
FROM   audit Where audit.server_response_code = '401' 
) AS Locked,
(
SELECT COUNT(audit.server_response_code)
FROM   audit Where audit.server_response_code = '403' 
) AS unlocked,
(
SELECT COUNT(audit.server_response_code)
FROM   audit Where audit.server_response_code = '490' 
) AS Passforget,
(
Select Count (audit.server_response_code)
From audit where audit.server_response_code = '491' 
) AS invalid 

查询工作正常,但是我想在四个语句中添加一个聚合where语句。我该怎么办?

2 个答案:

答案 0 :(得分:4)

使用case表达式进行条件计数:

select count(case when audit.server_response_code = '401' then 1 end) AS Locked,
       count(case when audit.server_response_code = '403' then 1 end) AS unlocked,
       count(case when audit.server_response_code = '490' then 1 end) AS Passforget,
       count(case when audit.server_response_code = '491' then 1 end) AS invalid 
from audit
where audit.server_response_code in ('401','403','490','491')

可能不需要WHERE子句,但可能会加快速度(取决于数据和索引。)

更新:根据要求“我想添加一个总和列,它总结所有计数,但它现在正在运行,我该怎么办?”

select count(case when audit.server_response_code = '401' then 1 end) AS Locked,
       count(case when audit.server_response_code = '403' then 1 end) AS unlocked,
       count(case when audit.server_response_code = '490' then 1 end) AS Passforget,
       count(case when audit.server_response_code = '491' then 1 end) AS invalid, 
       count(*) as total_count
from audit
where audit.server_response_code in ('401','403','490','491')

答案 1 :(得分:2)

简化你的逻辑!

select sum(case when a.server_response_code = '401' then 1 else 0 end) as locked,
       sum(case when a.server_response_code = '403' then 1 else 0 end) as unlocked,
       sum(case when a.server_response_code = '490' then 1 else 0 end) as Passforget,
       sum(case when a.server_response_code = '491' then 1 else 0 end) as Invalid
from audit a;

使用此结构,您可以轻松添加group by

或者,更简单的方法是将值放在不同的行中:

select a.server_response_code, count(*)
from audit a
group by a.server_response_code;

注意:我没有过滤您提到的四个代码。如果还有其他代码,您可以添加该过滤器。