2013-10-28 69 views
3

這是我的動態計算領域的查詢:總和MySQL查詢動態生成的字段

SELECT 5 * (`Mean (all)` +0.01735568)/(0.07268901) AS rank1, 
5 * (`CVaR 95` +0.51612)/(0.53212) AS rank2, 
5 * (`Hurst` - 0.2)/(0.7717653) AS rank3, 
5 * (`MaxDD` +6.200000762939453)/(16.200000762939) AS rank4, 
5 * (`Positive % 12` - 0.3)/(1) AS rank5 
FROM `quant1` 

它工作正常,但我需要添加另一個動態場等於秩1 +秩2 ... +因此,我添加了另一個字段,如

SELECT 5 * (`Mean (all)` +0.01735568)/(0.07268901) AS rank1, 
5 * (`CVaR 95` +0.51612)/(0.53212) AS rank2, 
5 * (`Hurst` - 0.2)/(0.7717653) AS rank3, 
5 * (`MaxDD` +6.200000762939453)/(16.200000762939) AS rank4, 
5 * (`Positive % 12` - 0.3)/(1) AS rank5, 
rank1+rank2+rank3+rank4+rank5 AS rank 
FROM `quant1` 

它會生成一個錯誤「unknown column rank1」。有趣的是,完全相同的查詢適用於MS Access。

我該如何解決這個問題?

謝謝!

回答

1

在MySQL中,你不能引用其他別名,BU T優可以在選擇定義變量,那麼試試這個來代替:

SELECT 
    @rank1 := 5 * (`Mean (all)` +0.01735568)/(0.07268901) AS rank1, 
    @rank2 := 5 * (`CVaR 95` +0.51612)/(0.53212) AS rank2, 
    @rank3 := 5 * (`Hurst` - 0.2)/(0.7717653) AS rank3, 
    @rank4 := 5 * (`MaxDD` +6.200000762939453)/(16.200000762939) AS rank4, 
    @rank5 := 5 * (`Positive % 12` - 0.3)/(1) AS rank5, 
    @rank1 + @rank2 + @rank3 + @rank4 + @rank5 AS rank 
FROM `quant1` 

這是醜陋的,但它的工作原理。

+0

它的最佳執行時間爲0.049秒。 – user2723490

2

在同一SELECT語句中,不能使用別名,把它放在一個子查詢中,而不是像這樣:

SELECT rank1, rank2, rank3, rank4, rank5, 
    rank1 + rank2 + rank3 + rank4 + rank5 AS rank 
FROM 
(

    SELECT 5 * (`Mean (all)` +0.01735568)/(0.07268901) AS rank1, 
    5 * (`CVaR 95` +0.51612)/(0.53212) AS rank2, 
    5 * (`Hurst` - 0.2)/(0.7717653) AS rank3, 
    5 * (`MaxDD` +6.200000762939453)/(16.200000762939) AS rank4, 
    5 * (`Positive % 12` - 0.3)/(1) AS rank5 
    FROM `quant1` 
) AS t 
+0

它的工作原理... 10,000行的執行時間是0.062秒,比下面的Mats Kindahl的解決方案略差。 – user2723490

+1

請注意,子查詢在歷史上對優化器來說不是很好。它在最新的MySQL版本中得到了改進,但它確實推動了優化器。 –

+0

@MatsKindahl - 是的,你是對的,謝謝你的提示:) –

1

你必須途徑。 1.使用這些查詢作爲子查詢:

select R.*,R.rank1+R.rank2+R.rank3+R.rank4+R.rank5 AS rank from (
SELECT 5 * (`Mean (all)` +0.01735568)/(0.07268901) AS rank1, 
5 * (`CVaR 95` +0.51612)/(0.53212) AS rank2, 
5 * (`Hurst` - 0.2)/(0.7717653) AS rank3, 
5 * (`MaxDD` +6.200000762939453)/(16.200000762939) AS rank4, 
5 * (`Positive % 12` - 0.3)/(1) AS rank5 
FROM `quant1` 
) as R 

或 2.在您的查詢 取代: 等級-1 +秩2 + rank3 + rank4 + RANK5 與(5 *(Mean (all) 0.01735568)/(0.07268901) )+(5 *(CVaR 95 0.51612)/(0.53212))..等..

+0

就個人而言,我不建議選項2 - 他們會非常快速地失去同步。使用子查詢可能是唯一的選擇。 –

+0

選項1生成錯誤:「錯誤代碼:1248 每個派生表都必須具有自己的別名」。您需要在末尾 – user2723490

+0

處添加「AS someTable」。添加別名 – baltov

0

嘗試一個子查詢,如:

SELECT *, rank1+rank2+rank3+rank4+rank5 AS rank 
FROM ( 
    SELECT 5 * (`Mean (all)` +0.01735568)/(0.07268901) AS rank1, 
    5 * (`CVaR 95` +0.51612)/(0.53212) AS rank2, 
    5 * (`Hurst` - 0.2)/(0.7717653) AS rank3, 
    5 * (`MaxDD` +6.200000762939453)/(16.200000762939) AS rank4, 
    5 * (`Positive % 12` - 0.3)/(1) AS rank5, 
    FROM `quant1` 
) QuantRank 
+0

第8行的錯誤代碼1064 – user2723490