Sql 其中,如果某个字段为空,则不计算的条件
我有一张如下表:Sql 其中,如果某个字段为空,则不计算的条件,sql,oracle,Sql,Oracle,我有一张如下表: Table Value ----------------------------------------- id attribute1 attribute2 attribute3 active 232 A null B Y 486 null A null N 986 null
Table Value
-----------------------------------------
id attribute1 attribute2 attribute3 active
232 A null B Y
486 null A null N
986 null null null Y
509 B C D N
824 null B C Y
712 A C null N
我需要获取id=232824并创建如下查询:
select id
from value
where active = 'Y'
and attribute1 is not null
or attribute2 is not null
or attribute3 is not null
但它不起作用
在where条件下,我没有使用id而混淆了。
我需要使用该属性和活动标志创建where条件(仅当所有属性都为空时不获取id)这非常简单:
select count(*)
from t
where attribute1 is not null or attribute2 is not null or attribute3 is not null;
编辑:
您只需要正确的括号:
select count(*)
from t
where active = 'Y' and
(attribute1 is not null or attribute2 is not null or attribute3 is not null);
你忘了括号
select id from value where active = 'Y'
and (attribute1 is not null or
attribute2 is not null or
attribute3 is not null)
不使用OR子句的另一种方法是
SELECT *
FROM value
WHERE active = 'Y'
AND DECODE(attribute1,NULL,0,1) + DECODE(attribute2,NULL,0,1)+DECODE(attribute3,NULL,0,1)>1;
下面是SQL小提琴
我希望我理解了你的问题。 您需要所有行,其中
active
等于Y
,并且属性列不包含null
select *
from value
where active = 'Y'
and attribute1 is not null
and attribute2 is not null
and attribute3 is not null
这正好返回您想要的2行(ID232和824)。您刚刚把and的和or的搞砸了。您声明需要一个从测试数据集中提取id的232和824的查询 下面是:
select id
from value
where attribute2='B'
or attribute3='B';