首页 > 解决方案 > 如何在 SQL Server 中编写以下条件

问题描述

我有一张这样的桌子

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

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

标签: sqlsql-serversql-server-2008tsql

解决方案


使用简单GROUP BYHAVING条件适用于currNo

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

结果

custID
00124
00125

推荐阅读