我们可以使用多计数(列)与SQL Server中每个计数的cluase

时间:2018-05-05 05:41:24

标签: sql sql-server

Select Category,COUNT(HId) as Ticket 
from tblHelpdeskCalls 
Group by Category

Select Category,COUNT(HId) as Processing 
from tblHelpdeskCalls 
where CallStatus='Processing' 
Group by Category

Select Category, COUNT(HId) as Accepted 
from tblHelpdeskCalls 
where CallStatus='Accepted' 
Group by Category

将其显示在单个声明中

3 个答案:

答案 0 :(得分:4)

使用条件聚合:

select category,
       count(*) Ticket,
       sum(case when CallStatus = 'Processing' then 1 else 0 end) Processing,
       sum(case when CallStatus = 'Accepted' then 1 else 0 end) Accepted
from tblHelpdeskCalls t
group by category;

答案 1 :(得分:1)

您仍然可以使用COUNT

SELECT category,
       Ticket     = COUNT(*),
       Processing = COUNT(CASE WHEN CallStatus = 'Processing' THEN HId END),
       Accepted   = COUNT(CASE WHEN CallStatus = 'Accepted'   THEN HId END)
FROM tblHelpdeskCalls
GROUP BY category;

匹配CASEWHEN的默认值为NULL,汇总函数跳过NULL值。

答案 2 :(得分:0)

首先,我们按类别和计数进行分组:

select category,
       count(*) Ticket
  from tblHelpdeskCalls
 group by category;

其次,第二,它区分了CallStatus(Processing / Accepted)的情况。我们可以使用" case"或"解码":

使用"" (由Yogesh Sharma和lad2025提出):

select category,
       count(*) Ticket,
       sum(case when CallStatus = 'Processing' then 1 else 0 end) Processing,
       sum(case when CallStatus = 'Accepted' then 1 else 0 end) Accepted
  from tblHelpdeskCalls
 group by category;

使用"解码":

select category,
       count(*) Ticket,
       sum( decode(CallStatus, 'Processing', 1, 0) ) Processing,
       sum( decode(CallStatus, 'Accepted'  , 1, 0) ) Accepted
  from tblHelpdeskCalls
 group by category;