pg14-sql基础(二)-排序与统计

排序

SELECT employee_id, first_name, last_name, hire_date, salary
FROM employees
ORDER BY first_name; --按字母,默认升序
ORDER BY hire_date ASC; --升序
ORDER BY hire_date DESC; --降序
SELECT employee_id, first_name, last_name, hire_date, salary
FROM employees
ORDER BY first_name, last_name DESC --姓按照升序排,名按照降序排

在这里插入图片描述

在这里插入图片描述

SELECT employee_id, first_name, last_name, hire_date, salary
FROM employees
ORDER BY 2, 3 DESC --也可输入要查询字段的顺序号码
SELECT employee_id, manager_id
FROM employees
ORDER BY manager_id DESC; --排序时null是最大的值

SELECT employee_id, manager_id
FROM employees
ORDER BY manager_id NULLS FIRST; --指定排序时null是第一

返回top

-- 前十名
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary
-- FETCH FIRST 10 ROWS ONLY;
LIMIT 10; --无相同值

pg14-sql基础(二)-排序与统计_第1张图片

SELECT first_name, last_name, salary
FROM employees
ORDER BY salary
FETCH FIRST 10 ROWS WITH TIES;
-- 返回数据包含相同值

pg14-sql基础(二)-排序与统计_第2张图片

SELECT first_name, last_name, salary
FROM employees
ORDER BY salary
OFFSET 10 ROWS --实现翻页,第一次1-10,第二次11-20,第三次,21-30
-- OFFSET 20 ROWS
-- OFFSET 30 ROWS
FETCH FIRST 10 ROWS ONLY;
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary
LIMIT 10 OFFSET 10; --同实现翻页
-- LIMIT 10 OFFSET 20;
-- LIMIT 10 OFFSET 20;

汇总统计

SELECT COUNT(*), SUM(salary), AVG(SALARY), MAX(salary), MIN(salary)
FROM employees;
-- 行数、和、平均、最大、最小
SELECT COUNT(*), COUNT(manager_id) FROM employees;
--因为实验表中有一名员工的manager_id为null,聚合函数会忽略null,但count(*)特殊

在这里插入图片描述

SELECT COUNT(DISTINCT manager_id) FROM employees; -- 聚合函数中的distinct会先去重
SELECT STRING_AGG(first_name, ';') FROM employees; --字符串聚合,以分号隔离

SELECT STRING_AGG(first_name, ';' ORDER BY first_name) FROM employees; --添加排序

你可能感兴趣的:(pg-sql,sql,排序统计)