2017-08-01 65 views
-1

我想要显示大于或等于80的温度,只有在天气场很热的情况下。如果天气场是任何其他值,则显示所有温度。情况何时满足条件那么哪里逻辑

SELECT field1, field2, etc, 

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

FROM dbo.table 

错误

I get an Incorrect Syntax near '>' 

我应该如何重新编写查询,使其工作?

+0

当天气炎热且温度低于80时,它应该显示什么? – Lamak

+0

它应显示所有字段(包括值大于或等于80的临时字段)。如果天气不热,则显示所有字段(包括包含所有值的临时字段) – user3062459

+1

您的案例表达式很混乱。一个case表达式用于返回一个单一的值,但你有“温度> 80”。也许你的案例表达是倒退?我只是无法做出你在这里输出的东西。 –

回答

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 
+0

我只想要温度> = 80,其中天气=热的 – user3062459

+0

是的,它只适用于这种方式,我将添加解释,它全部是布尔algerbra。 – GurV

+0

谢谢你的工作! – user3062459

0

写什么Gurwinder Singh正确建议会更明确的另一种方式:

select * 
from table 
where 
    (temperature >= 80 and weather = 'hot') 
    or 
    (weather != 'hot') 
-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℃时的温度。您可以改变其他值以返回空值