2012-09-18 49 views
0

我遇到問題。我想在我的SQL查詢IF語句使用,他們使用該聲明進一步的計算結果:在MySQL中使用IF語句以及使用語句結果的進一步計算

SELECT average_rating, number_of_ratings,  
    IF(number_of_ratings < 500 AND number_of_ratings > 100, 0.90, 
     IF(number_of_ratings>=500 AND number_of_ratings<=1000, 0.95, 
      IF(number_of_ratings>1000, 0.99, 0.80) 
     ) 
    ) AS rating_factor,  
    ROUND((rating_factor * average_rating), 4) AS factored_rating  
FROM table 
ORDER by factored_rating DESC 

但是,它不工作,並返回一個錯誤:未知列「rating_factor」'字段列表'

有沒有人有一個想法如何使它的工作?

在此先感謝。

+1

不能在同一語句引用一個別名列。你需要寫一個子查詢 – Kermit

+0

他的用法並不複雜。 –

+0

作爲一個'CASE'語句而不是嵌套的IFs將使它更易於閱讀恕我直言 –

回答

1

這應有助於:

SELECT a.average_rating, a.number_of_ratings, ROUND((a.rating_factor * a.average_rating), 4) AS factored_rating 
FROM 
    (SELECT average_rating, number_of_ratings,  
     IF(number_of_ratings < 500 AND number_of_ratings > 100, 0.90, 
      IF(number_of_ratings>=500 AND number_of_ratings<=1000, 0.95, 
       IF(number_of_ratings>1000, 0.99, 0.80) 
      ) 
     ) AS rating_factor 
    FROM table 
    ORDER by factored_rating DESC) a 
1

使用IF語句的結果你的配方食品中。我覺得我得到了括號的權利,但你應該看到的想法:如果你不同時需要rating_factor和factored_rating列

SELECT average_rating, number_of_ratings,  
    ROUND((
    IF(number_of_ratings < 500 AND number_of_ratings > 100, 0.90, 
     IF(number_of_ratings>=500 AND number_of_ratings<=1000, 0.95, 
      IF(number_of_ratings>1000, 0.99, 0.80) 
     ) 
    ) * average_rating), 4) as factored_rating  
FROM table 
ORDER by factored_rating DESC 
+0

是啊!這很好!謝謝。 – Stanislav

3

阿蘭的查詢會工作。 njk的查詢是subquerying的ANSI兼容版本。

但是,由於您使用的是MySQL,因此您可以使用臨時變量存儲值。我也簡化了你的IF條件。

SELECT 
    average_rating, 
    number_of_ratings, 
    @x := IF(number_of_ratings> 1000, 0.99, 
      IF(number_of_ratings>=500 , 0.95, 
      IF(number_of_ratings> 100 , 0.90, 
             0.80))) rating_factor, 
    ROUND((@x * average_rating), 4) AS factored_rating 
FROM mytable 
ORDER by factored_rating DESC 

這是SQLFiddle來顯示此查詢。
對於後人,下面複製了樣本。

drop table if exists mytable; 
create table mytable (
average_rating int, 
number_of_ratings int, 
factored_rating int); 
insert into mytable 
select 5,2,3 union all 
select 4,1,5 union all 
select 12,3,1 union all 
select 11,4,2 union all 
select 8,2,12; 

結果查詢

"average_rating";"number_of_ratings";"rating_factor";"factored_rating" 
"12";"3";"0.80";"9.6000" 
"11";"4";"0.80";"8.8000" 
"8";"2";"0.80";"6.4000" 
"5";"2";"0.80";"4.0000" 
"4";"1";"0.80";"3.2000" 
+0

哇!這個效果更好!非常感謝! – Stanislav