根据SQL Server中的条件计数

时间:2010-08-11 04:06:38

标签: sql sql-server tsql

有谁知道如何根据条件在SQL Server中进行计数。

示例:

如何为名为'system'的记录和表中的CaseID总记录进行列计数?

客户表

UserID     CaseID     Name
1          100        alan
1          101        alan
1          102        amy
1          103        system
1          104        ken
1          105        ken
1          106        system  

结果将如下所示:

UserID    TotalCaseID    TotalRecordsWithSystem
1         7              2

4 个答案:

答案 0 :(得分:93)

使用SUM / CASE ...

SELECT
    COUNT(*),  --total
    SUM(CASE WHEN name = 'system' THEN 1 ELSE 0 END) --conditional
FROM
    myTable

答案 1 :(得分:11)

我认为他在结果中需要用户ID

SELECT 
    userid,
    COUNT(*) as TotalcaseID, --total 
    SUM(CASE WHEN name = 'system' THEN 1 ELSE 0 END) as TotalRecordsWithSystem  
FROM 
    myTable 
group by userid

答案 2 :(得分:4)

select
userid,
count('x') as TotalCaseID,
count(case when name = 'system' then 'x' else null end) as TotalRecordsWithSystem
from CustomerTable
group by userid

答案 3 :(得分:0)

如果您使用的是SQL Server 2012+,则可以使用SUM/IIF

SELECT
    COUNT(*) AS Total,
    SUM(IIF(Name = 'system', 1, 0)) AS SystemTotal
FROM
    CustomerTable