Oracle的一條sql使用臨時表進行查詢

2021-08-28 20:43:12 字數 1705 閱讀 3714

with cte as(

select

c.sub_corp_name

,b.bus_path_name

,round(s.actual_day_run_total_mile / 1000, 2) as mile_already

,round(s.day_already_run_total_mile / 1000, 2) as current_mile

,decode(s.day_already_run_total_mile, 0, 0, round(s.actual_day_run_total_mile / s.day_already_run_total_mile * 100 ,2)) as rate

,rank() over (order by decode(s.day_already_run_total_mile, 0, 0, round(s.actual_day_run_total_mile / s.day_already_run_total_mile * 100 ,2))) rn

from nbbusits.t_bus_path_sta_data s,nbbusits.t_bus_path b,nbbusits.t_bus_path_company c

where 1=1

and update_time > to_date(to_char(sysdate,'yyyy/mm/dd'),'yyyy/mm/dd')

and s.bus_path_id = b.bus_path_id

and b.bus_path_name = c.bus_path_name

and c.sub_corp_name like '永平%'

and s.actual_day_run_total_mile > 0 and s.day_already_run_total_mile > 0

)select b.* from cte a

left join(

select

t.bus_path_name as category

,decode(series,'current_mile','計畫','mile_already','實際','rate','完成率') as series

,value

from cte unpivot(value for series in (mile_already, current_mile, rate)) t

left join nbbusits.t_on_duty_info d on t.bus_path_name = d.sub_corp_name

)bon a.bus_path_name = b.category

where 1=1

and rn <= 10

order by rn,category,series

使用到第乙個知識點,with *** as (),將一條sql語句的結果作為乙個臨時變數(臨時表)存在***,然後在下面就可以將***當成表來查詢使用,適用在複雜的又只想用一條sql完事的需求。因本案例需要使用到列轉行,並且需要在結果中以原本的某一列做排序,故用到with *** as,

另外用到列轉行unpivot、跳躍排序rank() over(order by...)、decode等函式

做為筆記記錄,另拓展了解dense_rank() over()、min()/max() over()、lead()/lag() over()、

Oracle中一條sql引發的血案(一)

血案sql如下 create table yw wg 17 as select distinct acc from yw wc cust 1715 a where a.acc not in select distinct acc from yw wc cust 17 b where a.acc b....

一條SQL的改寫

最近需求中需要實現這樣乙個功能 找主活動是未鎖定的,且已確認的子活動資料,表中資料的分布是這樣的 表中資料存放結構 主活動1 沒鎖定 子活動 主11 已確認 子活動 主22 已確認 主活動2 鎖定 子活動 主21 未確認 子活動 主22 已確認 1用 not exist實現 select t1.at...

一條sql 分類彙總

表結構 stuid stuname stucourse stugrade 001 a 語文 88 002 b 語文 89 003 a 數學 98 004 b 數學 100 005 a 英語 87 006 b 英語 86 mysql select groupid,stuid,stuname,cours...