Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 基于状态的SQL选择_Sql Server - Fatal编程技术网

Sql server 基于状态的SQL选择

Sql server 基于状态的SQL选择,sql-server,Sql Server,我有上表,希望选择那些状态为ok的ID。有没有一个简单的方法来实现这一点 在上表中,仅应选择ID=2,因为仅提及ID=2两次,状态为OK。ID=1具有“OK”状态,一旦处于“X”状态,则不应选择它 select ID from table where status = 'OK' 如果您只需要唯一的ID,请使用DISTINCT,下面的命令将起作用 select distinct ID from table where status = 'OK' and ID not in (Select

我有上表,希望选择那些状态为ok的ID。有没有一个简单的方法来实现这一点

在上表中,仅应选择ID=2,因为仅提及ID=2两次,状态为OK。ID=1具有“OK”状态,一旦处于“X”状态,则不应选择它

select ID from table where status = 'OK'
如果您只需要唯一的ID,请使用DISTINCT,下面的命令将起作用

   select distinct ID from table where status = 'OK' and ID not in (Select ID from table where 
   status <> 'OK')

有一些关于您的数据的信息尚未共享,例如每个Id是否始终有2行,是否可以有一行,多于2行

如果只想选择Id,一个简单的解决方案是将GROUPBY与having子句一起使用,并在Id值的总数与状态为OK的数字匹配的情况下仅筛选Id


这个问题是关于SQL的基本能力的——如果您对SQL一无所知,请从阅读教程开始。使用SQL查询数据库,最基本的查询是:select*from[table],它从表中选择所有行和列。若要筛选结果,请使用WHERE子句。@user172283您应该在问题中编辑该附加要求,而不是将其作为注释发布。这在很大程度上改变了解决方案。
select id
from #X
group by id
having Count(*)=Sum(case when status='ok' then 1 else 0 end)