2016-04-13 116 views
0

我從表中選擇字段比較值,例如:Mysql Select case case and field comparison

Select FieldA,FieldB,(FieldC-FIeldD) as Difference 

並且現在想要實際選擇賦予差值字段的值,例如,

When Difference=0 then 'North' 
When Different>0 and Difference<=90 then 'NorthEast' 
When Difference=90 then 'South' 

等,但我無法如何插入選擇。我已經在更新這樣做是成功的,但選擇逃避我

回答

0

我覺得一個Sub-Select查詢將工作做好在這裏。

目前你的說法是這樣的:

Select FieldA,FieldB,(FieldC-FIeldD) as Difference from <TABLE> 

相反,你可以在這個子選擇這樣的:

select * from 
(
Select FieldA,FieldB,(FieldC-FIeldD) as Difference from <TABLE> 
) sub_table 

現在你可以做你的case語句在最外層的SELECT語句:

select 
CASE 
    When Difference=0 then 'North' 
    When Difference>0 and Difference<=90 then 'NorthEast' 
    When Difference=90 then 'South' 
END as answer 
from 
(
Select FieldA,FieldB,(FieldC-FIeldD) as Difference from <TABLE> 
) 
+0

在第二個'WHEN'中,您不需要'Difference> 0',因爲個案是按順序嘗試的(我假設消極情況不會發生)。您還有一個名字爲「Different」的拼寫錯誤。 – Barmar

+0

固定,謝謝。從askers錯字複製:) –

0

一種方法是使用子查詢:

SELECT FieldA, FieldB, 
CASE 
    WHEN Difference = 0 THEN 'North' 
    WHEN Difference > 0 AND <= 90 THEN 'NorthEast' 
    WHEN Difference = 90 THEN'South' 
END AS Foo 
FROM (
    Select FieldA, FieldB, (FieldC-FIeldD) AS Difference 
) 
+0

這是無效的語法。你不能寫'WHEN> 0'。 – Barmar

+0

修正語法... – WillardSolutions

+0

現在它與其他答案一樣。 – Barmar