SQL入门教程:从零开始掌握数据库查询语言
-- 创建一个简单的表格,用于演示查询操作
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR(50),
Department VARCHAR(50),
Salary DECIMAL(10, 2)
);
-- 向表格中插入数据
INSERT INTO Employees (ID, Name, Department, Salary) VALUES
(1, 'John Doe', 'Sales', 50000.00),
(2, 'Jane Smith', 'Marketing', 52000.00),
(3, 'Mike Brown', 'Sales', 48000.00),
(4, 'Jill Johnson', 'HR', 45000.00);
-- 查询所有员工的信息
SELECT * FROM Employees;
-- 查询所有销售部门员工的姓名和薪水
SELECT Name, Salary FROM Employees WHERE Department = 'Sales';
-- 查询薪水高于45000的员工姓名和薪水
SELECT Name, Salary FROM Employees WHERE Salary > 45000;
-- 查询薪水介于45000到50000之间的员工姓名和薪水
SELECT Name, Salary FROM Employees WHERE Salary BETWEEN 45000 AND 50000;
-- 按部门分组,并计算每个部门的平均薪水
SELECT Department, AVG(Salary) FROM Employees GROUP BY Department;
-- 按部门分组,并计算每个部门薪水总和
SELECT Department, SUM(Salary) FROM Employees GROUP BY Department;
-- 查询薪水排名第二的员工(不使用ORDER BY)
SELECT * FROM Employees WHERE Salary = (SELECT DISTINCT Salary FROM Employees ORDER BY Salary DESC LIMIT 1 OFFSET 1);
-- 删除表格
DROP TABLE Employees;
这段代码展示了如何在SQL中创建一个简单的表格、插入数据、执行基本的查询操作、分组和排序数据,以及如何使用子查询。这对于学习者来说是一个很好的起点。
评论已关闭