PostgreSQL GROUP BY 学习笔记
本文将介绍 PostgreSQL 中的 GROUP BY 语句,该语句可以根据指定的列对查询结果进行分组。
语法
Copy CodeSELECT column1, column2, ...
FROM table_name
GROUP BY column1, column2, ...
示例
假设我们有以下表格:
books 表格:
id | name | author | publish_date |
---|---|---|---|
1 | The Great Gatsby | F. Scott Fitzgerald | 1925-04-10 |
2 | To Kill a Mockingbird | Harper Lee | 1960-07-11 |
3 | 1984 | George Orwell | 1949-06-08 |
4 | Animal Farm | George Orwell | 1945-08-17 |
5 | Romeo and Juliet | William Shakespeare | 1597-01-04 |
使用 GROUP BY 对作者进行分组并计算每个作者的书籍数量:
Copy CodeSELECT author, COUNT(id) as book_count
FROM books
GROUP BY author;
将会得到以下结果:
author | book_count |
---|---|
F. Scott Fitzgerald | 1 |
Harper Lee | 1 |
George Orwell | 2 |
William Shakespeare | 1 |
注意:在 GROUP BY 语句中,所有未在 GROUP BY 中指定的列都必须在聚合函数 (例如上面的 COUNT) 中进行聚合计算,否则查询将失败。