我在SQL中有一个带有以下架构的表
SessionKey | FieldName | FieldValue
-----------+-------------------+------------
1 | resroom_Adults | 2
1 | resroom_Children | 0
2 | resroom_Adults | 4
2 | resroom_Children | 0
3 | resroom_Adults | 3
3 | resroom_Children | 2
我正在尝试在查询中评估2个场景
fieldname ='res_adult'和fieldvalue> 3
fieldname ='res_adult'和fieldvalue> = 2且fieldname ='res_child'和fieldvalue> 2
如果满足任何条件,我的代码应该返回1,否则为0。
我的查询是
IF Exists
(select *
from ReservationContractRulesObjectDefinitions
where sessionkey=@sessionkey
and ((FieldName = 'resroom_Adults' and fieldvalue > 3)
OR ((FieldName = 'resroom_Adults' and fieldvalue >=2)
AND (FieldName = 'resroom_Children' and fieldvalue>2)
)
)
)
begin select 1 End Else begin Select 0 End
在上面的查询中,仅检查第一个条件。
但是,从不检查第二个条件。
请有人帮助我。
答案 0 :(得分:1)
我想你想要这样的东西:
select (case when max(case when FieldName = 'resroom_Adults' and fieldvalue > 3 then 1 else 0 end) > 0
then 1
when max(case when FieldName = 'resroom_Adults' and fieldvalue >= 2 then 1 else 0 end) > 0 and
max(case when FieldName = 'resroom_Children' and fieldvalue > 2 then 1 else 0 end) > 0
then 1
else 0
end)
from ReservationContractRulesObjectDefinitions
where sessionkey = @sessionkey ;