我想写一个查询,在这里我只能选择特定的行,而忽略SQL中的一些不同的行

问题描述

我有一个表,其中BrandId在具有不同状态(例如待处理正在运行)的表中重复多次。 我想要状态仅待处理的行。如果任何状态未决且正在运行的BrandId,则我们不希望在输出中显示此信息,我想忽略这些BrandId,并且不希望在输出中显示该行。

Sample Input Table Data

我只希望状态为待定的那些BrandId。

有人可以告诉我有关查询的信息以获取所需的结果吗?

Sample output data that we want

解决方法

不存在用于过滤那些仅具有未决记录的记录,如下所示:

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
)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...