我想写一个查询,其中我只能选择特定的行,并希望忽略SQL中的一些不同的行
我有一个表,其中BrandId在一个表中重复多次,该表具有不同的状态,如挂起和运行。 我想要状态仅为挂起的行。如果有任何BrandId的状态是挂起的,并且正在运行,那么我们不希望在输出中使用它,我希望忽略这些BrandId,不希望在输出中使用该行 我只想要那些BrandId的状态只是挂起的 有人能告诉我有关查询的信息以获得所需的结果吗我想写一个查询,其中我只能选择特定的行,并希望忽略SQL中的一些不同的行,sql,sql-server,azure-sql-database,Sql,Sql Server,Azure Sql Database,我有一个表,其中BrandId在一个表中重复多次,该表具有不同的状态,如挂起和运行。 我想要状态仅为挂起的行。如果有任何BrandId的状态是挂起的,并且正在运行,那么我们不希望在输出中使用它,我希望忽略这些BrandId,不希望在输出中使用该行 我只想要那些BrandId的状态只是挂起的 有人能告诉我有关查询的信息以获得所需的结果吗 使用“不存在”筛选那些只有挂起的记录,如下所示: SELECT distinct ID, BRANDID, STATUS FROM TABLE1 A WHERE
使用“不存在”筛选那些只有挂起的记录,如下所示:
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) = 'pending' -- no 'running'
您可能需要将
id
添加到分组依据
您可以使用不存在
作为处于运行
状态的品牌
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
)
“婚前”和“跑步”是你仅有的状态吗?有没有其他表品牌
?
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
)