接上篇,只为收藏
二、组函数(AVG()、SUM()……)、分组函数(GROUP BY)、排序(ORDER BY)
1、组函数:
AVG(Column)
例:
--统计全体员工的平均工资
SELECT AVG(salary) 平均工资
FROM employees;
SUM(Column)
例:
--统计工资支出总额
SELECT SUM(salary) 工资支出总额
FROM employees;
MAX(Column)
例:
--统计最高工资
SELECT MAX(salary) 最高工资
FROM employees;
MIN(Column)
例:
--统计最低工资
SELECT MIN(salary) 最低工资
FROM employees;
COUNT(Column)
例:
--统计员工总数
SELECT COUNT(employee_id) 员工总数
FROM employees;
2、分组函数:
GROUP BY Column
HAVING Condition
--例:统计员工平均工资高于10000的部门
SELECT AVG(salary), department_id
FROM employees
GROUP BY department_id
HAVING AVG(salary) > 10000;
3、排序:
ORDER BY
--例1:将员工工资按升序排列
SELECT last_name, salary
FROM employees
ORDER BY salary;
--例2:按员工入职时间长短降序排列
SELECT last_name, hire_date
FROM employees
ORDER BY hire_date DESC;
--例3:查找工资最高的前三名员工
SELECT TOP 3 salary, last_name
FROM employees
ORDER BY salary DESC;
三、子查询
SELECT Column
FROM Table
WHERE express operator (SELECT Col
FROM Tab
WHERE condition);
例1:
--查找工资与Jones工资相同的员工信息
SELECT *
FROM employees
WHERE salary = (SELECT salary
FROM employees
WHERE last_name = 'Jones');
例2:
--查找员工表里,工资最高的员工的所有信息
SELECT *
FROM employees
WHERE salary = (SELECT MAX(salary)
FROM employees );
例3:
--查找最高工资高于10000,并且最低工资低于4000的部门
SELECT DISTINCT department_name
FROM department
WHERE department_id IN (SELECT department_id
FROM employees
GROUP BY department_id
HAVING MAX(salary) > 10000 AND MIN(salary) < 4000);
例4:
--选出表中后10行
SELECT *
FROM employees
WHERE employee_id NOT IN (SELECT TOP (((SELECT COUNT(employee_id)
FROM employees)) - 10) employee_id
FROM employees);
四、增加(INSERT INTO Table VALUES=())、删除(DELETE FROM Table)、更改数据(UPDATE Table SET Column=key)
1、增加、插入数据:
INSERT INTO Table (Column1, Column2……)
VALUES (Element1, Element2……);
例1:
--向部门表里插入编号为101的人事部
INSERT INTO department
VALUES (101, '人事部', NULL, NULL);
例2:
--向员工表里插入编号为999,名字叫“测试时代”的新员工
INSERT INTO employees (employee_id, last_name)
VALUES (999, '测试时代');
2、删除数据:
DELETE FROM Table
WHERE Condition;
例:
--删除部门表里标号为101的部门
DELETE FROM department
WHERE department_id = 101;
3、更新数据:
UPDATE Table
SET Column = Value
WHERE Condition;
例:
--将部门号为80的部门,改为部门号为101,部门名为”人力资源部“
UPDATE department
SET department_id = 101,
department_name = '人力资源部'
WHERE department_id = 80;