複雜sql,還沒學儲存過程

2021-09-24 10:04:32 字數 2498 閱讀 2226

複雜sql

涉及:行轉列,排名,差值,排名變化,left join

select

'排名',

a0,concat( '收聽份額(%)', a1 ),

concat( '收聽份額(%)', a2 ),

'收聽份額(%)增減值',

'排名變化',

concat( '收聽率(%)', a1 ),

concat( '收聽率(%)', a2 ),

'收聽率(%)增減值'

from

z_20190610102908765

where

bbh = '三月'

limit 1 union

select

* from

( select

rank,

a0,fe,

fe1,

fe1 - fe,

rank_change,

sl,sl1,

sl1 - sl

from

( select

@pm := @pm + 1 rank,

b.*

from

(select

id,a0,

fe,fe1,

fe1 - fe,

sl,sl1,

sl1 - sl

from

(select

id,a0,

max( case a4 when '收聽份額' then a1 else 0 end ) fe,

max( case a4 when '收聽份額' then a2 else 0 end ) fe1,

max( case a4 when '收聽率' then a1 else 0 end ) sl,

max( case a4 when '收聽率' then a2 else 0 end ) sl1

from

z_20190610102908765

where

bbh = '三月'

and a5 = '揚州'

group by

a0 ) a

) b,

( select @pm := 0 ) r

order by

sl1 + 0 desc,

fe1 + 0 desc

) b0

left join (

select

b.id,

rank - rank1 as rank_change

from

(select

a.*,

@fe_num := @fe_num + 1 as rank

from

(select

id,a0,

max( case a4 when '收聽份額' then a1 else 0 end ) fe,

max( case a4 when '收聽份額' then a2 else 0 end ) fe1,

max( case a4 when '收聽率' then a1 else 0 end ) sl,

max( case a4 when '收聽率' then a2 else 0 end ) sl1

from

z_20190610102908765

where

bbh = '三月'

and a5 = '揚州'

group by

a0 ) a,

( select @fe_num := 0 ) r

order by

sl + 0 desc,

fe + 0 desc

) bleft join (

select

a.*,

@fe1_num := @fe1_num + 1 as rank1

from

(select

id,a0,

max( case a4 when '收聽份額' then a1 else 0 end ) fe,

max( case a4 when '收聽份額' then a2 else 0 end ) fe1,

max( case a4 when '收聽率' then a1 else 0 end ) sl,

max( case a4 when '收聽率' then a2 else 0 end ) sl1

from

z_20190610102908765

where

bbh = '三月'

and a5 = '揚州'

group by

a0 ) a,

( select @fe1_num := 0 ) r

order by

sl1 + 0 desc,

fe1 + 0 desc

) c on b.id = c.id

) b1 on b0.id = b1.id

) a3

SQL儲存過程

什麼是儲存過程呢?定義 將常用的或很複雜的工作,預先用sql語句寫好並用乙個指定的名稱儲存起來,那麼以後要叫資料庫提供與已定義好的儲存過程的功能相同的服務時,只需呼叫execute,即可自動完成命令。講到這裡,可能有人要問 這麼說儲存過程就是一堆sql語句而已啊?microsoft公司為什麼還要新增...

sql儲存過程

概念 sql server提供了一種方法,它可以將一些固定的操作集中起來由sql server資料庫伺服器來完成,以實現某個任務,這種方法就是儲存過程。儲存過程是sql語句和可選控制流語句的預編譯集合,儲存過程在資料庫中可由應用程式通過乙個呼叫執行,而且允許使用者申明變數 有條件的執行以及其它強大的...

SQL儲存過程

儲存過程 1.返回值 create proc example4 as begin declare 返回值 int select 返回值 sum 庫存量 from 產品 return 返回值 endgo 接受這個返回值必須要用變數來接收,如 declare 接收值 int exec 接收值 examp...