Cómo usar count y group by en la misma instrucción select
Tengo una consulta sql select que tiene un grupo by. Quiero contar todos los registros después del grupo por declaración. ¿Hay alguna forma de hacerlo directamente desde sql? Por ejemplo, al tener una tabla con los usuarios quiero seleccionar las diferentes ciudades y el total número de usuarios
select town, count(*) from user
group by town
Quiero tener una columna con todas las ciudades y otra con el número de usuarios en todas las filas.
Un ejemplo del resultado para tener 3 ciudades y 58 usuarios en total es :
Town Count
Copenhagen 58
NewYork 58
Athens 58
11 answers
Esto hará lo que quieras (lista de ciudades, con el número de usuarios en cada una):
select town, count(town)
from user
group by town
Puede usar la mayoría de funciones agregadas cuando se usa GROUP BY
.
Update (following change to question and comments)
Puede declarar una variable para el número de usuarios y establecerla en el número de usuarios y luego seleccionarla con eso.
DECLARE @numOfUsers INT
SET @numOfUsers = SELECT COUNT(*) FROM user
SELECT DISTINCT town, @numOfUsers
FROM user
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
2018-05-28 09:17:32
Puede utilizar COUNT(DISTINCT ...)
:
SELECT COUNT(DISTINCT town)
FROM user
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-10-30 09:57:59
La otra manera es:
/* Number of rows in a derived table called d1. */
select count(*) from
(
/* Number of times each town appears in user. */
select town, count(*)
from user
group by town
) d1
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-10-14 23:36:21
Con Oracle se pueden utilizar funciones analíticas:
select town, count(town), sum(count(town)) over () total_count from user
group by town
Sus otras opciones son usar una subconsulta:
select town, count(town), (select count(town) from user) as total_count from user
group by town
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-04-28 07:02:23
Si quieres ordenar por cuenta (suena simple, pero no puedo encontrar una respuesta en la pila de cómo hacer eso) puedes hacer:
SELECT town, count(town) as total FROM user
GROUP BY town ORDER BY total DESC
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-12-18 18:22:45
Puedes usar DISTINTO dentro del CONTEO como lo que milkovsky dijo
En mi caso:
select COUNT(distinct user_id) from answers_votes where answer_id in (694,695);
Esto extraerá el conteo de votos de respuesta considerados el mismo user_id que un conteo
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-10-06 05:47:31
Sé que este es un post antiguo, en SQL Server:
select isnull(town,'TOTAL') Town, count(*) cnt
from user
group by town WITH ROLLUP
Town cnt
Copenhagen 58
NewYork 58
Athens 58
TOTAL 174
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-03-12 00:31:04
Si desea seleccionar la ciudad y el número total de usuarios, puede usar esta consulta a continuación:
SELECT Town, (SELECT Count(*) FROM User) `Count` FROM user GROUP BY Town;
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-10-14 07:19:31
Intente el siguiente código:
select ccode, count(empno)
from company_details
group by ccode;
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-04-06 09:47:26
Si desea utilizar la opción Seleccionar Todas Las Consultas Con Recuento, pruebe esto...
select a.*, (Select count(b.name) from table_name as b where Condition) as totCount from table_name as a where where Condition
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-05 12:27:15
Diez respuestas no eliminadas; la mayoría hacen no hacer lo que el usuario pidió. La mayoría de las respuestas mal-leer la pregunta como pensando que hay 58 usuarios en cada ciudad en lugar de 58 en total. Incluso los pocos que son correctos no son óptimos.
mysql> flush status;
Query OK, 0 rows affected (0.00 sec)
SELECT province, total_cities
FROM ( SELECT DISTINCT province FROM canada ) AS provinces
CROSS JOIN ( SELECT COUNT(*) total_cities FROM canada ) AS tot;
+---------------------------+--------------+
| province | total_cities |
+---------------------------+--------------+
| Alberta | 5484 |
| British Columbia | 5484 |
| Manitoba | 5484 |
| New Brunswick | 5484 |
| Newfoundland and Labrador | 5484 |
| Northwest Territories | 5484 |
| Nova Scotia | 5484 |
| Nunavut | 5484 |
| Ontario | 5484 |
| Prince Edward Island | 5484 |
| Quebec | 5484 |
| Saskatchewan | 5484 |
| Yukon | 5484 |
+---------------------------+--------------+
13 rows in set (0.01 sec)
SHOW session status LIKE 'Handler%';
+----------------------------+-------+
| Variable_name | Value |
+----------------------------+-------+
| Handler_commit | 1 |
| Handler_delete | 0 |
| Handler_discover | 0 |
| Handler_external_lock | 4 |
| Handler_mrr_init | 0 |
| Handler_prepare | 0 |
| Handler_read_first | 3 |
| Handler_read_key | 16 |
| Handler_read_last | 1 |
| Handler_read_next | 5484 | -- One table scan to get COUNT(*)
| Handler_read_prev | 0 |
| Handler_read_rnd | 0 |
| Handler_read_rnd_next | 15 |
| Handler_rollback | 0 |
| Handler_savepoint | 0 |
| Handler_savepoint_rollback | 0 |
| Handler_update | 0 |
| Handler_write | 14 | -- leapfrog through index to find provinces
+----------------------------+-------+
En el contexto del OP:
SELECT town, total_users
FROM ( SELECT DISTINCT town FROM canada ) AS towns
CROSS JOIN ( SELECT COUNT(*) total_users FROM canada ) AS tot;
Puesto que solo hay una fila desde tot
, el CROSS JOIN
no es tan voluminoso como podría ser de otra manera.
El patrón habitual es COUNT(*)
en lugar de COUNT(town)
. El esto último implica verificar que town
no sea null, lo cual es innecesario en este contexto.
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
2018-07-07 19:55:21