如何在SQL Server中为以下内容编写条件

时间:2018-08-14 06:42:55

标签: 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!= 1但可以具有currNo> 1的custID

下面是我的代码;

select distinct custID from test
where currNo != 1 and currNo > 1

上述查询的结果:

00123
00124
00125
00126

例外结果:

00124
00125

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

5 个答案:

答案 0 :(得分:3)

使用在GROUP BY上应用的简单HAVINGcurrNo条件

SELECT custID FROM #test
GROUP BY custID
HAVING MIN(currNo)<>1

结果

custID
00124
00125

答案 1 :(得分:2)

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

答案 2 :(得分:1)

不使用

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

http://sqlfiddle.com/#!18/ee7c0e/10

custID
00124
00125

答案 3 :(得分:1)

使用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

的另一种方法
div.relative {
    position: relative;
    width: 400px;
    height: 1000px;
    border: 3px solid #73AD21;
} 

div.absolute {
    position: absolute;
    top: 80px;
    right: 0;
    width: 200px;
    height: 100px;
    border: 3px solid #73AD21;
}
h2{
position: fixed;
background-color: white;
}

DEMO

答案 4 :(得分:0)

从#test中选择custID 按客户分组 具有MIN(currNo)<> 1和COUNT(currNo)> 1