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; --降序
sql复制代码
SELECT employee_id, first_name, last_name, hire_date, salary
FROM employees
ORDER BY first_name, last_name DESC --姓按照升序排,名按照降序排
sql复制代码
SELECT employee_id, first_name, last_name, hire_date, salary
FROM employees
ORDER BY 2, 3 DESC --也可输入要查询字段的顺序号码
sql复制代码
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
sql复制代码
-- 前十名
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary
-- FETCH FIRST 10 ROWS ONLY;
LIMIT 10; --无相同值
sql复制代码
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary
FETCH FIRST 10 ROWS WITH TIES;
-- 返回数据包含相同值
sql复制代码
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;
sql复制代码
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary
LIMIT 10 OFFSET 10; --同实现翻页
-- LIMIT 10 OFFSET 20;
-- LIMIT 10 OFFSET 20;
汇总统计
sql复制代码
SELECT COUNT(*), SUM(salary), AVG(SALARY), MAX(salary), MIN(salary)
FROM employees;
-- 行数、和、平均、最大、最小
sql复制代码
SELECT COUNT(*), COUNT(manager_id) FROM employees;
--因为实验表中有一名员工的manager_id为null,聚合函数会忽略null,但count(*)特殊
sql复制代码
SELECT COUNT(DISTINCT manager_id) FROM employees; -- 聚合函数中的distinct会先去重
sql复制代码
SELECT STRING_AGG(first_name, ';') FROM employees; --字符串聚合,以分号隔离
SELECT STRING_AGG(first_name, ';' ORDER BY first_name) FROM employees; --添加排序