MySQL分组
概述
GROUP BY子句将具有相同值的行分组为汇总行。它通常与COUNT、SUM、AVG、MIN、MAX等聚合函数一起使用以生成分组汇总。
GROUP BY语法
sql
基本分组
单列分组
sql
-- Group by single column
-- Group by country
-- Count per category多列分组
sql
-- Group by multiple columns
-- Detailed grouping聚合函数
计数
sql
-- Count all rows
-- Count non-NULL values
-- Count distinct values
-- Count per group求和
sql
-- Sum of values
-- Sum per group
-- Sum with condition平均值
sql
-- Average value
-- Average per group
-- Round average最小值和最大值
sql
-- Minimum value
-- Maximum value
-- First and last dateHAVING子句
基本HAVING
sql
-- Filter groups with HAVING
-- Having with aggregateHAVING与WHERE比较
| 方面 | WHERE | HAVING |
|---|---|---|
| Filters | Rows before grouping | Groups after grouping |
| With GROUP BY | Before group | After group |
| Aggregate functions | Cannot use | Can use |
| Performance | Faster | Slower |
sql
-- WHERE filters rows before grouping
-- HAVING filters groups after grouping复杂HAVING
sql
-- Multiple conditions
-- With OR带JOIN的GROUP BY
sql
-- Group with JOIN
-- Complex JOIN with GROUP BY汇总
基本汇总
sql
-- Generate subtotals and grand total
-- Result includes:
-- - Details by category and subcategory
-- - Subtotals by category
-- - Grand totalGROUPING()函数
sql
-- Identify NULL from ROLLUP
-- 1 = generated by ROLLUP (supertotal row)
-- 0 = normal grouping row立方体
CUBE语法
sql
-- Generate all combinations
-- Creates summaries for:
-- - All combinations of category and subcategory
-- - Each category total
-- - Each subcategory total
-- - Grand total分组集
基本分组集
sql
-- Specific groupings等效的ROLLUP和CUBE
sql
-- ROLLUP equivalent
-- Equivalent to:
-- CUBE equivalent
-- Equivalent to:GROUP BY与DISTINCT
sql
-- Count distinct values per group
-- Complex distinct count实用示例
销售报表
sql
-- Daily sales summary用户统计
sql
-- Users by activity level产品分析
sql
-- Products by category with stats性能考虑
索引使用
sql
-- Index on GROUP BY columns helps
-- Index for WHERE + GROUP BY优化技巧
sql
-- Filter before grouping
-- Use appropriate data types
-- Numeric grouping is faster than string grouping
-- Avoid SELECT * with GROUP BY
-- Select only necessary columns故障排除
常见问题
sql
-- Column not in GROUP BY or aggregate
-- Error: Expression #X of SELECT list is not in GROUP BY
-- Solution: Add column to GROUP BY or use aggregate
-- Unexpected results
-- Check: GROUP BY columns, aggregate functions
-- Verify: Filter conditions in WHERE vs HAVING调试
sql
-- Check group formation
-- Verify aggregate values小结
GROUP BY子句提供:
分组:按列值对行分组 聚合:COUNT、SUM、AVG、MIN、MAX HAVING:分组后过滤组 高级分组:ROLLUP、CUBE、分组集 性能:在分组列上使用索引 用例:报表、分析、汇总
上一个:ORDER BY
下一个:JOINs