乙個SQL語句的變化過程

2022-02-26 17:43:14 字數 2528 閱讀 5733

1  原始語句

select c.parentid,a.area_dm, a.airport_dm, ('        ' + b.qc) as airportname,sum(jcn) as totaljcn, 

sum(cr + et + crwh + etwh)  as totallk, sum(hw + yj)  as totalhy, sort = 1 

from airportproduces_2006 a 

left join airports b on a.airport_dm = b.airport_dm 

left join areas as c on c.area_dm = a.area_dm

left join hbxz as d on a.hbxz = d.char_code

where a.produce_date >= '2006-01-01' and a.produce_date <= '2006-02-28'

and d.char_sort = '運輸'

and  (a.area_dm = '51')  group by a.area_dm, a.airport_dm, b.qc, c.parentid,d.char_sort

2 變化要求:當sum(jcn)的時候不考慮where條件中的d.char_sort

變化第一步:

select c.parentid,a.area_dm, a.airport_dm, ('        ' + b.qc) as airportname,sum(jcn) as totaljcn, 

case when d.char_sort = '運輸' then sum(cr + et + crwh + etwh) else 0 end as totallk, 

case when d.char_sort = '運輸' then sum(hw + yj) else 0 end as totalhy, sort = 1 into #temp

from airportproduces_2006 a 

left join airports b on a.airport_dm = b.airport_dm 

left join areas as c on c.area_dm = a.area_dm

left join hbxz as d on a.hbxz = d.char_code

where a.produce_date >= '2006-01-01' and a.produce_date <= '2006-02-28'

and (a.area_dm = '51') group by a.area_dm, a.airport_dm, b.qc, c.parentid,d.char_sort

select parentid,area_dm,airport_dm,airportname, 

sum(totaljcn) as totaljcn,sum(totallk) as totallk,sum(totalhy) as totalhy,sort = 1 from #temp2 

group by area_dm, airport_dm, parentid, airportname

這個步驟運用臨時表  將結果放入臨時表 然後再分組統計

2 演化步驟二

綜合第一步,可以寫出第二步,一條語句

select parentid,area_dm,airport_dm,airportname, 

sum(totaljcn) as totaljcn,sum(totallk) as totallk,sum(totalhy) as totalhy,sort = 1 from (

select c.parentid,a.area_dm, a.airport_dm, ('        ' + b.qc) as airportname,

sum(jcn) as totaljcn, 

case when d.char_sort = '運輸' then sum(cr + et + crwh + etwh) else 0 end as totallk, 

case when d.char_sort = '運輸' then sum(hw + yj) else 0 end as totalhy, sort = 1 from

airportproduces_2006 a 

left join airports b on a.airport_dm = b.airport_dm 

left join areas as c on c.area_dm = a.area_dm

left join hbxz as d on a.hbxz = d.char_code

where a.produce_date >= '2006-01-01' and a.produce_date <= '2006-02-28'

and (a.area_dm = '51') group by a.area_dm, a.airport_dm, b.qc, c.parentid,d.char_sort

) as sumtable group by area_dm, airport_dm, parentid, airportname

乙個不會的SQL語句

12.有兩個表a 和b 均有key 和value 兩個字段,如果b 的key 在a 中也有,就把b 的value 換為a 中對應的value 這道題的sql 語句怎麼寫?update b set value select value from awhere a.key b.key where exi...

乙個神奇的SQL語句

題目是這樣的 分別往這兩張表中新增3條資料。查詢營業額最高商家的商品總價與營業額最低商家的商品總價差是多少 5分 create view vm2 as select price limit num as total money b.id from business b,goods g where b...

用SQL語句獲得乙個儲存過程返回的表

定義乙個儲存過程如下 proc dbo test1 idint asselect1as id,abc asname union allselect idas id,zzz asname 返回兩行資料.現在想用sql語句來呼叫這個儲存過程,並把他返回的表放入變數中.可以如下做 declare tabl...