¿Es posible especificar una condición en Count ()?


¿Es posible especificar una condición en Count()? Me gustaría contar solo las filas que tienen, por ejemplo, "Administrador" en la columna Posición.

Quiero hacerlo en la sentencia count, no usando WHERE; estoy preguntando por ello porque necesito contar ambos Gerentes y Otros en el mismo SELECT (algo como Count(Position = Manager), Count(Position = Other)) así que WHERE no me sirve de nada en este ejemplo.

Author: Michael, 2009-09-09

12 answers

Si no puede limitar la consulta con una cláusula where, puede usar el hecho de que el agregado count solo cuenta los valores no nulos:

select count(case Position when 'Manager' then 1 else null end)
from ...

También puedes usar el agregado sum de una manera similar:

select sum(case Position when 'Manager' then 1 else 0 end)
from ...
 508
Author: Guffa,
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
2009-09-09 14:34:49

Asumiendo que no desea restringir las filas que se devuelven porque también está agregando otros valores, puede hacerlo de la siguiente manera:

select count(case when Position = 'Manager' then 1 else null end) as ManagerCount
from ...

Digamos que dentro de la misma columna que tenía valores de Gerente, Supervisor y Líder de Equipo, podría obtener los recuentos de cada uno de esta manera:

select count(case when Position = 'Manager' then 1 else null end) as ManagerCount,
    count(case when Position = 'Supervisor' then 1 else null end) as SupervisorCount,
    count(case when Position = 'Team Lead' then 1 else null end) as TeamLeadCount,
from ...
 192
Author: RedFilter,
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
2009-09-09 14:31:33

@Guffa ' s respuesta es excelente, solo señalar que tal vez es más limpio con una declaración IF

select count(IF(Position = 'Manager', 1, NULL)) as ManagerCount
from ...
 17
Author: Hivenfour,
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
2016-05-20 10:19:44

Depende de lo que quieras decir, pero la otra interpretación del significado es donde quieres contar filas con un cierto valor, pero no quieres restringir la SELECCIÓN a SOLO esas filas...

Lo harías usando SUM () con una cláusula, como esta en lugar de usar COUNT(): por ejemplo,

SELECT SUM(CASE WHEN Position = 'Manager' THEN 1 ELSE 0 END) AS ManagerCount,
    SUM(CASE WHEN Position = 'CEO' THEN 1 ELSE 0 END) AS CEOCount
FROM SomeTable
 15
Author: AdaTheDev,
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
2009-09-09 14:33:09

También puede usar la palabra clave Pivot si está utilizando SQL 2005 o superior

Más info y de Technet

SELECT *
FROM @Users
PIVOT (
    COUNT(Position)
    FOR Position
    IN (Manager, CEO, Employee)
) as p

Conjunto de datos de ensayo

DECLARE @Users TABLE (Position VARCHAR(10))
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('CEO')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
 12
Author: Matthew Whited,
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
2009-09-09 15:03:04

Sé que esto es muy antiguo, pero me gusta el NULLIF truco para tales escenarios, y no encontré inconvenientes hasta ahora. Simplemente vea mi ejemplo copy & pasteable, que no es muy práctico, pero muestra cómo usarlo.

NULLIF podría darte un pequeño impacto negativo en el rendimiento, pero supongo que aún debería ser más rápido que las subconsultas.

DECLARE @tbl TABLE ( id [int] NOT NULL, field [varchar](50) NOT NULL)

INSERT INTO @tbl (id, field)
SELECT 1, 'Manager'
UNION SELECT 2, 'Manager'
UNION SELECT 3, 'Customer'
UNION SELECT 4, 'Boss'
UNION SELECT 5, 'Intern'
UNION SELECT 6, 'Customer'
UNION SELECT 7, 'Customer'
UNION SELECT 8, 'Wife'
UNION SELECT 9, 'Son'

SELECT * FROM @tbl

SELECT 
    COUNT(1) AS [total]
    ,COUNT(1) - COUNT(NULLIF([field], 'Manager')) AS [Managers]
    ,COUNT(NULLIF([field], 'Manager')) AS [NotManagers]
    ,(COUNT(1) - COUNT(NULLIF([field], 'Wife'))) + (COUNT(1) - COUNT(NULLIF([field], 'Son'))) AS [Family]
FROM @tbl

Comentarios apreciados: -)

 3
Author: z00l,
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
2016-02-12 17:39:21

Creo que puede usar una cláusula WHERE simple para seleccionar solo el recuento de algún registro.

 1
Author: NawaMan,
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
2009-09-09 14:30:14

Quieres decir esto:

SELECT Count(*) FROM YourTable WHERE Position = 'Manager'

Si es así, entonces sí que funciona!

 1
Author: Dana,
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
2009-09-09 14:30:19
SELECT COUNT(*) FROM bla WHERE Position = 'Manager'
 0
Author: Peter,
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
2009-09-09 14:30:06

Nota con PrestoDB SQL (de Facebook), hay un atajo:

Https://prestodb.io/docs/current/functions/aggregate.html

Count_if (x) → bigint

Devuelve el número de valores de entrada VERDADEROS. Este función es equivalente a count (CASO CUANDO x ENTONCES 1 FINAL)

 0
Author: Thomas Decaux,
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
2017-12-11 14:10:08

Simplemente agregue una cláusula WHERE y estará listo.

 -3
Author: Kyle Rozendo,
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
2009-09-09 14:30:01

Usando esto obtendrás el conteo de gerentes

Select Position, count(*) as 'Position Counter'
from your_table 
group by Position 
 -6
Author: Rafael,
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
2015-03-18 15:03:33