一. with as 简介:
with as其实就是一个子查询, 使用它可以增强sql的可读性,同时因为该查询只执行一次,并将结果存储在用户临时表空间中,
可以多次引用,增强性能。
二. with as 用法:
with temp as ( select * from xxx ) select * from temp;
二. with as 实战:
查询出部门的总薪水大于所有部门平均总薪水的部门:
部门表s_dept, 员工表s_emp;
-- step1:查询出部门名和部门的总薪水 with dept_costs as( select a.name,sum(b.salary) dept_total from s_dept a,s_emp b where a.id=b.dept_id group by a.name ), -- step2:利用上一个with查询的结果,计算部门的平均总薪水 avg_costs as( select sum(dept_total)/count(*) dept_avg from dept_costs ) -- step3:从两个with查询中比较并且输出查询结果 select name,dept_total from dept_costs where dept_total > ( select dept_avg from avg_costs ) order by name;
时间: 2024-11-04 00:08:42