问题描述
我有一个表,其中BrandId在具有不同状态(例如待处理和正在运行)的表中重复多次。 我想要状态仅待处理的行。如果任何状态未决且正在运行的BrandId,则我们不希望在输出中显示此信息,我想忽略这些BrandId,并且不希望在输出中显示该行。
我只希望状态为待定的那些BrandId。
有人可以告诉我有关查询的信息以获取所需的结果吗?
解决方法
不存在用于过滤那些仅具有未决记录的记录,如下所示:
SELECT distinct ID,BRANDID,STATUS FROM TABLE1 A WHERE STATUS = 'pending'
AND NOT EXISTS(SELECT 1 FROM TABLE1 B WHERE A.ID = B.ID AND A.BRANDID = B.BRANDID AND B.STATUS = 'Running');
,
select brandid,max(status)
from tab
group by brandid
having max(status) = min(status) -- only one status exists
and max(status) = 'pending' -- and it's 'pending'
如果只有“待处理”和“正在运行”:
select brandid,max(status)
from tab
group by brandid
having max(status) = 'pending' -- no 'running'
您可能想将id
添加到group by
您可以将not exists
用于具有running
状态的品牌
select t.*
from table t
where not exists (
select 1
from table
where status = 'Running'
and brandId = t.brandId
)
and status = 'pending'
使用聚合的另一种方法是
select t.*
from table t
where t.brandId in (
select brandId
from table
group by brandId
having sum(case when status = 'pending' then 1 else 0 end) > 0
and sum(case when status = 'Running' then 1 else 0 end) = 0
)