Recuento basado en la condición en SQL Server


¿Alguien sabe cómo puedo hacer un recuento en SQL Server basado en la condición.

Ejemplo:

¿Cómo puedo hacer un recuento de columnas para los registros con el nombre 'system' y los registros de caseid totales en la tabla??

Tabla de clientes

userid     caseid     name
1          100        alan
1          101        alan
1          102        amy
1          103        system
1          104        ken
1          105        ken
1          106        system  

El resultado se mostrará como a continuación:

UseeID    TotalcaseID    TotalRecordsWithSystem
1         7              2
Author: marc_s, 2010-08-11

3 answers

Utilice SUM/CASE...

SELECT
    COUNT(*),  --total
    SUM(CASE WHEN name = 'system' THEN 1 ELSE 0 END) --conditional
FROM
    myTable
 78
Author: gbn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-11 04:10:08

Creo que quería id de usuario en los resultados

SELECT 
    userid,
    COUNT(*) as TotalcaseID, --total 
    SUM(CASE WHEN name = 'system' THEN 1 ELSE 0 END) as TotalRecordsWithSystem  
FROM 
    myTable 
group by userid
 10
Author: Matt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-30 03:08:56
select
userid,
count('x') as TotalCaseID,
count(case when name = 'system' then 'x' else null end) as TotalRecordsWithSystem
from CustomerTable
group by userid
 3
Author: kage,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-12 03:43:35