Agrupar por SQL: Explicado con Ejemplos

Guía práctica de GROUP BY en SQL: domina COUNT, SUM, AVG, MIN y MAX, HAVING y JOIN para crear informes claros y útiles con ejemplos y casos de negocio.

27 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Agrupar por SQL explicado con ejemplos y aplicado a informes prácticos

Cuando trabajas con bases de datos, a menudo necesitas resúmenes en lugar de filas crudas. Agrupar filas que comparten un mismo valor y luego aplicar funciones agregadas permite responder preguntas como Cuantos pedidos hizo cada cliente, Cual es la venta total por departamento o Cual es la nota media por alumno. Para eso sirve GROUP BY en SQL.

Funciones principales y para que sirven

COUNT() Cuenta el numero de filas en cada grupo. Ejemplo: SELECT customer_id, COUNT(*) AS order_count FROM Orders GROUP BY customer_id;

SUM() Suma valores numericos por grupo. Ejemplo: SELECT customer_id, SUM(total_amount) AS total_spent FROM Orders GROUP BY customer_id;

AVG() Calcula el promedio por grupo. Ejemplo con JOIN para mostrar nombres: SELECT c.name, AVG(o.total_amount) AS avg_order FROM Customers c JOIN Orders o ON c.customer_id = o.customer_id GROUP BY c.name;

MIN() y MAX() Devuelven el valor minimo y maximo por grupo. Ejemplos: SELECT c.name, MIN(o.total_amount) AS min_order FROM Customers c JOIN Orders o ON c.customer_id = o.customer_id GROUP BY c.name; y SELECT c.name, MAX(o.total_amount) AS max_order FROM Customers c JOIN Orders o ON c.customer_id = o.customer_id GROUP BY c.name;

HAVING Filtra resultados despues de agrupar, a diferencia de WHERE que filtra filas antes de la agregacion. Ejemplo: SELECT c.name, SUM(o.total_amount) AS total_spent FROM Customers c JOIN Orders o ON c.customer_id = o.customer_id GROUP BY c.name HAVING SUM(o.total_amount) > 50;

Uso de JOIN con GROUP BY: cuando quieres mostrar etiquetas legibles en lugar de identificadores, une tablas y agrupa por la columna de nombre. Esto mejora la interpretacion de los informes.

Ejemplo de tablas simples para practicar

Customers: customer_id, name. Orders: order_id, customer_id, total_amount. Con esas dos tablas puedes calcular numero de pedidos por cliente, gasto total por cliente, pedido minimo y maximo, y el promedio de compra.

Consejos practicos

1 Selecciona siempre las columnas no agregadas que aparecen en GROUP BY. 2 Usa HAVING para condiciones sobre grupos. 3 Combina con JOIN para sustituir ids por nombres y mejorar la claridad del informe. 4 Emplea las funciones COUNT SUM AVG MIN MAX segun el tipo de resumen que necesites.

Herramientas visuales

Si prefieres construir consultas sin teclear todo desde cero, herramientas visuales como constructores de consultas permiten arrastrar tablas, seleccionar columnas y aplicar agregados mientras muestran la sentencia SQL generada. Esto acelera el aprendizaje y evita errores al crear GROUP BY complejos.

Como puede ayudar Q2BSTUDIO

En Q2BSTUDIO somos una empresa de desarrollo de software y aplicaciones a medida especializada en soluciones a medida para empresas. Ofrecemos servicios que abarcan desde desarrollo de aplicaciones multiplataforma hasta soluciones avanzadas de inteligencia artificial y ciberseguridad. Podemos diseñar pipelines de datos que generen informes basados en GROUP BY optimizados para su negocio, integrar cuadros de mando con Power BI y automatizar procesos de obtencion y agregacion de datos.

Para proyectos de inteligencia de negocio y visualizacion de datos trabajamos con herramientas como Power BI y Business Intelligence y ofrecemos integracion con servicios en la nube. Si tu iniciativa incluye modelos predictivos o agentes IA, nuestro equipo de especialistas en IA para empresas y agentes IA puede ayudarte a extraer valor de los datos agregados y a poner en producción modelos que complementen los informes.

Tambien cubrimos necesidades de ciberseguridad y pentesting, servicios cloud aws y azure, servicios inteligencia de negocio, automatizacion de procesos, y desarrollos de software a medida y aplicaciones a medida para proyectos a cualquier escala.

Resumen rapido

GROUP BY agrupa filas con un mismo valor y se combina con COUNT SUM AVG MIN MAX para resumir informacion. Usa HAVING para filtrar despues de la agregacion y JOIN para mostrar etiquetas en lugar de ids. Estas tecnicas son esenciales para totales, promedios y reportes por categoria en cualquier proyecto de analisis de datos.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat