All technological notes.
GROUP BY StatementGROUP BY
GROUP BY 语句用于结合聚合函数,根据一个或多个列对结果集进行分组。GROUP BY 解决的是 Group function 不能和列名共同 Query 的问题. 如果没有 GROUP BY, Group function 只能在 Query 中返回单一结果; 适用了 Group BY, 则 Group function 可以和列名结合返回多列多行结果.Syntax
SELECT category_col_1, category_col_2, aggregate_function(data_col)
FROM tb_name
WHERE condition
# the order doesn't matter
# category column can be function, eg: DATE(payment_date)
GROUP BY category_col_1, category_col_2
ORDER BY aggregate_function(data_col)
LIMIT num
-- JOIN情况下的Group By
SELECT a.col1, b.col2 SUM(a.col * a.col) "Alias" --列出结果需要的列名和多列函数
FROM tbA a JOIN tbB b ON (a.colcommon = b.colcommon) --指出联结的条件
GROUP BY a.col1, b.col2 --指出需要分组的列名,注意该处col1和col2必须列出,因为他们都在SELECT语句中出现
ORDER BY a.col1, b.col2; --排序
GROUP BY clause
FROM or WHERE statement.GROUP BY clause. 别名不能再 GROUP BY 语句中出现.In SELECT statement, columns must either have an aggregate function or be in the GROUP BY call. select 中的列名, 要么适用于聚合函数,要么在 GROUP BY 中声明.
Categorical Column
GROUP BYORDER BY
HAVING statement: Filter aggregate resultHAVING statement
Syntax:
SELECT category_col_1, category_col_2, aggregate_function(column_name)
FROM tb_name
WHERE condition
GROUP BY category_col_1, category_col_2
HAVING aggregate_function(column_name) operator value
ORDER BY aggregate_function(data_col)
LIMIT num
Having condition
HAVING之后执行.SELECT customer_id
, SUM(amount) # SUM aggregation function
FROM payment
GROUP BY customer_id
HAVING COUNT(amount) > 40 # COUNT aggregation function
ORDER BY 2 DESC;
对比: HAVING vs WHERE
WHERE clause restricts the records that will appear in the query.
WHERE clause cannot contain any grouping functions. where 不能使用聚合函数HAVING clause will specify which groups will be displayed in the results. The HAVING clause is a WHERE clause for groups
使用:
如果同时涉及筛选条件, 分组, 分组条件时, 三个语句的顺序:
WHEREGROUPHAVING计算顺序:
WHERE clause filters the data before grouping, whereas the HAVING clause filters the groups after the grouping occurs. 先 where 过滤, 再 having 过滤思考思路:
WHERE;GROUP BY;HAVING;