1. 程式人生 > >sql with 使用-臨時表

sql with 使用-臨時表

1、業務場景:

 有些需求需要對多個表分別統計出結果,然後使用每個表統計的結果進行彙總,這個時候臨時表就發揮作用了。

2、簡單使用:

with 
t1 as(select empId,yearMonth,sum(salary) as'a'
from tb_salary where yearMonth = '2017-01'
group by empId,yearMonth

),

t2 as (select empId,yearMonth,sum(salary) as'a'
from tb_salary where yearMonth = '2017-02'
group by empId,yearMonth ),

t as (select t1.empId e1, t2.empId e2, t1.empId e3, isnull(t1.yearMonth,'2017-01') m1,
 isnull(t2.yearMonth,'2017-02') m2, '與上月差額
' m3 ,isnull(t1.a,'0') a1, isnull(t2.a,'0') a2,emp.staffNo,emp.staffName,emp.orgPath
from t1 right join t2 on t1.empId = t2.empId RIGHT JOIN tb_employees emp on t2.empId = emp.empId) 

-- 行轉列
select 1 n,tt.e2,tt.staffNo,tt.m1,tt.a1 from (select * from from t) tt union all
select 2 n,tt.e2,tt.staffNo,tt.m2,tt.a2 from (select * from from t) tt union all
select 3 n,tt.e2,tt.staffNo,tt.m3,(tt.a2-tt.a1) a3 from (select * from from t  where t.staffNo = '4289') tt
ORDER BY t.e2 desc,n asc;