簡體   English   中英

如何優化SQL a / avg(a)?

[英]How to optimise SQL a/avg(a)?

在我的SQL腳本中,我想標准化來自像這樣的子查詢的值

select y/avg(y) from (
   select x*z as y from test_table
)T

我知道這個解決方案會起作用

select y/avg_y from (
       select id, x*z as y from test_table
    )T
join(
  select avg(y) as avg_y
  from(
    select x*z as y from test_table
  )a
)T2

但是我不想重復兩次,有什么好主意嗎?

ANSI標准機制是:

select y / (avg(y) over ())
from (select x*z as y from test_table) T

要么:

select x * z / (avg(x * z) over ())
from test_table;

這使用了大多數數據庫都支持的窗口功能。

編輯:

MySQL不支持窗口功能。 如果您不想重復兩次計算,則可以使用帶有變量的技巧:

select y / (@sy / @rn)
from (select x*z as y,
             @rn := if(x*z is not null, @rn + 1, @rn),
             @s := if(x*z is not null, @s + x*z, @s)
      from test_table t cross join
           (select @rn := 0, @sy := 0) params
     ) t;

在外部查詢中使用變量之前,應先為子查詢創建變量。

而且,一種寫不帶變量的查詢的簡單方法不會使用太多子查詢:

select (t.x * t.z)/ a.avg_y
from test_table t cross join
     (select avg(x*z) as avg_y
      from test_table
     ) a;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM