Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.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_Sql Server 2008_Tsql - Fatal编程技术网

如何在SQL Server中写入以下条件

如何在SQL Server中写入以下条件,sql,sql-server,sql-server-2008,tsql,Sql,Sql Server,Sql Server 2008,Tsql,我有一张这样的桌子 create table test (custID varchar(20), currNo int) insert into test values ('00123', 1) ,('00123', 2), ('00123', 3), ('00124', 2), ('00124', 3), ('00125', 3),('00125', 4), ('00126', 1),('00126', 3) 我只需要选择那些有currNo!

我有一张这样的桌子

create table test (custID varchar(20), currNo int)
insert into test 
values ('00123', 1) ,('00123', 2), ('00123', 3),
        ('00124', 2), ('00124', 3),
        ('00125', 3),('00125', 4),
        ('00126', 1),('00126', 3)
我只需要选择那些有currNo!=1但它可以有currNo>1

下面是我的一段代码

select distinct custID from test
where currNo != 1 and currNo > 1
上述查询的结果:

00123
00124
00125
00126
例外结果:

00124
00125
请更正我的查询以获得所需的输出。提前谢谢

使用简单的分组方式,并在currNo上应用条件

select distinct contractid from test
where not exists(select * from test t2 where t2.contractid=test.contractid and t2.currNo=1)
不使用

  select distinct custID from test
where custID not in (select custID from test t2 where t2.custID=test.custID and t2.currNo=1)

使用左连接的另一种方法

从测试中选择custID 按客户ID分组
如果MINcurrNo1和COUNTcurrNo>1,则预期结果中也有1,并且也大于1。那么你到底想在这里做什么呢?00123和00126都包含值currNo>1,所以它出现在结果集yes上,但123和126也有currNo=1,所以我不需要。我只需要custId而不是1,但它可以有>1顺便问一下-是收缩的还是custId?您的表上显示了custID和查询CONSTRACTID。很抱歉,这是一个输入错误,我现在更改了。感谢您的回答。快速性能测试也显示这是最快的,特别是如果custID上有索引,currno。我真的很惊讶。是的。我也测试了所有答案的执行成本,这一个似乎没有指数好。然而,这将花费很多时间。谢谢
custID
00124
00125
  select distinct custID from test
where custID not in (select custID from test t2 where t2.custID=test.custID and t2.currNo=1)
custID
00124
00125
select distinct t1.custID 
from test t1
left join test t2 on t1.custid=t2.custid and t2.currno=1
where t2.custid is  null