Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

SQL - Group By

Back


GROUP BY Statement

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; --排序

HAVING statement: Filter aggregate result

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

TOP