【问题标题】:How to write condition for below in SQL Server如何在 SQL Server 中编写以下条件
【发布时间】:2018-08-14 06:42:54
【问题描述】:

我有一张这样的桌子

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

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

【问题讨论】:

  • 预期结果中也有 1 并且也大于 1。那么你到底想在这里做什么?
  • 00123 ,00126 都包含值 currNo>1 所以它出现在您的结果集中
  • 是的,但是 123 和 126 也有 currNo =1 所以我不需要那个。我只需要 custId 而不是 1 但它可以有 >1

标签: sql sql-server sql-server-2008 tsql


【解决方案1】:

使用简单的GROUP BYHAVING 条件应用于currNo

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

结果

custID
00124
00125

【讨论】:

  • 快速性能测试也表明这也是最快的,尤其是在 (custid,currno) 上有索引的情况下。实际上让我感到惊讶。
  • 是的。我也测试了所有答案的执行成本,这个没有索引似乎很好。但是 Distinct 会花费很多时间。谢谢
【解决方案2】:
select distinct contractid from test
where not exists(select * from test t2 where t2.contractid=test.contractid and t2.currNo=1)

【讨论】:

  • 顺便问一下 - 它是contractID还是custID?您的表显示 custID 和您的查询 contractID。
  • 抱歉是错字,我现在改了。感谢您的回答
【解决方案3】:

不使用

  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

【讨论】:

    【解决方案4】:

    使用LEFT JOIN的另一种方法

    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
    

    DEMO

    【讨论】:

      【解决方案5】:

      从 #test 中选择客户 ID 按客户 ID 分组 有 MIN(currNo)1 AND COUNT(currNo) > 1

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-25
        • 1970-01-01
        • 2019-05-18
        • 2013-11-21
        • 2016-05-16
        • 2013-09-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多