¿Cómo uso el Grupo T-SQL Por


Sé que necesito tener (aunque no se por qué) una cláusula GROUP BY al final de una consulta SQL que use cualquier función agregada como count, sum, avg, etc:

SELECT count(userID), userName
FROM users
GROUP BY userName

¿Cuándo sería útil GROUP BY, y cuáles son las ramificaciones de rendimiento?

Author: Martin Smith, 2008-08-05

5 answers

Para recuperar el número de widgets de cada categoría de widgets que tiene más de 5 widgets, puede hacer esto:

SELECT WidgetCategory, count(*)
FROM Widgets
GROUP BY WidgetCategory
HAVING count(*) > 5

La cláusula "tener" es algo que la gente a menudo olvida, en lugar de optar por recuperar todos sus datos para el cliente e iterar a través de él allí.

 31
Author: Chris Farmer,
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
2012-11-27 13:33:37

GROUP BY es similar a DISTINCT en que agrupa varios registros en uno.

Este ejemplo, tomado de http://www.devguru.com/technologies/t-sql/7080.asp , enumera productos distintos en la tabla de productos.

SELECT Product FROM Products GROUP BY Product

Product
-------------
Desktop
Laptop
Mouse
Network Card
Hard Drive
Software
Book
Accessory

La ventaja de GROUP BY over DISTINCT, es que puede darte control granular cuando se usa con una cláusula HAVING.

SELECT Product, count(Product) as ProdCnt
FROM Products
GROUP BY Product
HAVING count(Product) > 2

Product      ProdCnt
--------------------
Desktop          10
Laptop            5
Mouse             3
Network Card      9
Software          6
 13
Author: Seibar,
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
2008-08-19 14:02:49

Group By obliga a rellenar todo el conjunto antes de que se devuelvan los registros (ya que es una ordenación implícita).

Por esa razón (y muchas otras), nunca use un Grupo By en una subconsulta.

 3
Author: Stu,
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
2008-08-05 19:01:10

Contar el número de veces que se usan etiquetas podría ser un ejemplo de Google:

SELECT TagName, Count(*)
AS TimesUsed
FROM Tags
GROUP BY TagName ORDER TimesUsed

Si simplemente desea un valor distinto de las etiquetas, preferiría usar la instrucción DISTINCT.

SELECT DISTINCT TagName
FROM Tags
ORDER BY TagName ASC
 2
Author: GateKiller,
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-12-01 18:16:24

AGRUPAR POR también ayuda cuando desea generar un informe que promediará o sumará un montón de datos. Puede AGRUPAR por el ID del departamento y la SUMA de todos los ingresos por ventas o AVG el recuento de ventas para cada mes.

 0
Author: Dillie-O,
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
2008-08-05 19:00:39