2013-02-01 91 views
0

我正在尋找一種解決方案,可以根據字段值直接在我的sql語句中獲取結果。根據sql語句中的其他字段選擇正確的字段

例如,如果我有以下結構:

calculated_result  result_one  result_two  result_three 
1      2.50   3.40   2.90 
2      1.90   2.00   3.90 
1      1.30   2.23   1.50 

然後我想進行搜索,它應該返回所有結果,其中calculated_result爲1和result_one是高於2.30且小於或等於2.65 。

問題是,我不知道如何返回適合用戶搜索的行。

calculated_result = 1應該檢查result_one比行內容 calculated_result = 2應該檢查result_two比行內容 等

希望是有意義更大和更小的大和小。

+0

給我們您現在使用的SQL語句...我們不做作業 –

+0

您是否嘗試過使用CASE? – Kermit

+0

問題是,我不知道如何做到這一點。任何人可以給我一些提示或只是幫助,而不是那種評論? :-) –

回答

4
select * 
from myTable 
where (calculated_result = 1 and result_one between 2.30 and 2.650) 
or  (calculated_result = 2 and result_two between 2.30 and 2.650) 
or  (calculated_result = 3 and result_three between 2.30 and 2.650) 

,或者,如果你想使用case

select * 
from myTable 
where case 
      when calculated_result = 1 then result_one 
      when calculated_result = 2 then result_two 
      when calculated_result = 3 then result_three 
     end between 2.30 and 2.650 
+0

該解決方案完美無缺,謝謝! –

0

試試這個

SELECT 
     * 
FROM 
     table_name 
WHERE 
     calculated_result = 1 AND 
     result_one > 2.30 AND 
     result_one <= 2.65 
+0

這錯過了「選擇[正確]字段」位。這個問題有點難以破譯。 – 2013-02-01 18:39:48

0

另:

select * 
from myTable 
where calculated_result in (1, 2, 3) and 
(result_one between 2.30 and 2.650 or result_two between 2.30 and 2.650 
or result_three between 2.30 and 2.650) 
; 

DEMO

+0

這會錯過「選擇[正確]字段」位。 – 2013-02-01 18:39:16

+0

@pst感謝您指出':)'順便說一句[Demo在這裏沒有任何查詢返回](http://sqlfiddle.com/#!2/af6d5/5) – bonCodigo

1

您可以嘗試使用CASE operator

SELECT * FROM yourTable 
WHERE (CASE 
    WHEN calculated_result = 1 THEN result_one 
    WHEN calculated_result = 2 THEN result_two 
END) > 2.3 
AND (CASE 
    WHEN calculated_result = 1 THEN result_one 
    WHEN calculated_result = 2 THEN result_two 
END) <= 2.65 
相關問題