在PostgreSQL(psql)中,要对数据进行分组,可以使用GROUP BY
子句
employees
的表,包含id
、name
、age
和department
字段:CREATE TABLE employees (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INTEGER,
department VARCHAR(255)
);
INSERT INTO employees (name, age, department) VALUES
('Alice', 30, 'HR'),
('Bob', 25, 'IT'),
('Charlie', 35, 'IT'),
('David', 28, 'HR');
GROUP BY
子句对数据进行分组。例如,我们要按部门对员工进行分组,并计算每个部门的员工数量:SELECT department, COUNT(*) as num_employees
FROM employees
GROUP BY department;
这将返回以下结果:
department | num_employees
------------+---------------
HR | 2
IT | 2
GROUP BY
子句中列出这些列。例如,我们要按部门和年龄对员工进行分组,并计算每个部门和年龄的员工数量:SELECT department, age, COUNT(*) as num_employees
FROM employees
GROUP BY department, age;
这将返回以下结果:
department | age | num_employees
------------+-----+---------------
HR | 30 | 1
HR | 28 | 1
IT | 25 | 1
IT | 35 | 1
这就是如何在psql数据库中使用GROUP BY
子句对数据进行分组的方法。希望对您有所帮助!