满足条件的情况那么逻辑

时间:2017-08-01 18:23:20

标签: sql-server

我希望显示的温度大于或等于80,仅在天气炎热时才会显示。如果天气场是任何其他值,则显示所有温度。

SELECT field1, field2, etc, 

CASE 
   WHEN weather = 'hot' THEN temperature >= 80
   ELSE temperature 
END

FROM dbo.table

错误

I get an Incorrect Syntax near '>' 

我应该如何重新编写查询才能使其正常工作?

3 个答案:

答案 0 :(得分:4)

您想要过滤行。所以它应该是where条款。

select *
from table
where temperature >= 80
    or weather != 'hot'

where子句的解释:

condition a = { weather == hot },
    so not_a = { weather != hot }
condition b = { temperature >= 80 }

你想要的是天气炎热,温度> = 80的所有行,当它不热时,那么所有温度:

这使得:

 = a.b + not_a
 = (a + not_a).(b + not_a)
 = (true).(b + not_a)
 = b + not_a
 = temperature >= 80 or weather != hot

所以写作

where temperature >= 80 or weather != hot

相当于

where (weather = 'hot' and temperature >= 80) or weather != hot

答案 1 :(得分:0)

撰写正确提出的Gurwinder Singh内容的另一种方式更明确:

select *
from table
where 
    (temperature >= 80 and weather = 'hot')
    or
    (weather != 'hot')

答案 2 :(得分:-1)

试试这个案例

SELECT field1, field2, etc, 

CASE 
   WHEN weather = 'hot' and  temperature >= 80 then temperature
   ELSE 0 -- Or null, it will depend on your logic 
END

FROM dbo.table

此案例仅显示天气炎热且温度大于80时的温度。您可以更改其他值以返回Null