本文將簡單介紹with子句的格式和用法
1、目的
通過創建一張(或多張)臨時表,實現數據的抽離,從而方便進行數據的比較
2、格式
//創建2張臨時表,並在這2張臨時表的基礎上進行查詢
with
temporary_table1_name(column_name,column_name) as
(select xxx
from xxx),
temporary_table2_name(column_name,column_name) as
(select xxx
from xxx)
select xxx
from temporary_table1_name,temporary_table2_name;
在上述語句中
temporary_table_name及其后面的column_name 都可以由自己指定
注意:創建的臨時表僅可以用於此次查詢,並不會寫入數據庫的物理內存中
3、實例
在上述的instructor表中,實現以下查詢:
找出 院系總工資 高於 所有院系的平均總工資的 院系名稱
思路如下:
(1)創建臨時表1,使用group by和SUM函數計算各個院系的總工資;
(2)創建臨時表2,對臨時表1的所有行 求平均值,從而得到所有院系的平均總工資;
(3)用常規的select+where語句在2張臨時表的基礎上進行查詢
with
dept_total(dept_name,value) as
(select dept_name, SUM(salary)
from instructor
group by dept_name),
dept_total_avg(value) as
(select AVG(salary)
from dept_total)
select dept_name
from dept_total, dept_total_avg
where dept_total.value>=dept_total_avg.value;
結果示意圖如下: