Mysql选择case语句和字段比较

时间:2016-04-13 15:39:53

标签: mysql case

我从具有字段比较值的表中进行选择,例如

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'

等但是我无法将其插入到Select中。我已经在更新中成功完成了这项工作,但Select退出了我

2 个答案:

答案 0 :(得分: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
)

答案 1 :(得分: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

现在,您可以在最外面的select语句中执行case语句:

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>
)