在SELECT子句中使用子查询:
-- 查询每个部门的平均工资
SELECT department_id, (SELECT AVG(salary) FROM employees WHERE department_id = d.department_id) AS avg_salary
FROM departments d;
在FROM子句中使用子查询:
-- 查询每个部门的总工资和平均工资
SELECT d.department_id, total_salary, avg_salary
FROM departments d
JOIN (SELECT department_id, SUM(salary) AS total_salary, AVG(salary) AS avg_salary FROM employees GROUP BY department_id) e
ON d.department_id = e.department_id;
在WHERE子句中使用子查询:
-- 查询工资高于平均工资的员工
SELECT employee_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
在HAVING子句中使用子查询:
-- 查询工资高于平均工资的部门
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING AVG(salary) > (SELECT AVG(salary) FROM employees);
这些是一些简单的SQLite子查询示例,演示了如何在不同的查询子句中使用子查询来实现更复杂的查询逻辑。在编写子查询时,请确保子查询返回的结果是标量值或表(如果在FROM子句中使用)。
转载请注明出处:http://www.pingtaimeng.com/article/detail/9173/SQLite