2016-11-21 76 views
2

所以我用這個查詢計數驗證錯誤的數目在我的數據庫:骨料凡多選擇查詢的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語句這適用於四個陳述。我該怎麼辦?

+0

你可以在'SELECT'外面添加一個'WHERE' - 這是你的意思嗎? –

+0

我嘗試使用where外部select語句,但它給了我一個錯誤,指出from子句丟失,我使用了from子句但它沒有工作 –

+0

查看我想要添加的聚合的'filter()'子句 –

回答

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子句也許不是必要的,但可以加快速度(取決於數據和索引)。

UPDATE:根據要求「我想添加一個總和列,總結所有的數字,但它現在工作,我該怎麼做?」

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') 
+0

一個總和列,總結所有的計數,但它現在的工作,我怎麼能做到這一點? –

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; 

注:我沒有過濾對於你提到的四個代碼。如果有其他代碼,則可以添加該過濾器。