Tsql 选择未设置标志的所有记录

Tsql 选择未设置标志的所有记录,tsql,sql-server-2012,Tsql,Sql Server 2012,如何查找hasPaid标志未设置为0的所有bookingNo 无法让它工作。我应该得到2-4-8号预订,HasPaid标志未设置为1 非常感谢 if object_id('tempdb..#testFlag') is not null drop table #testFlag create table #testFlag (BookingNo int, HasPaid bit) insert into #testFlag (BookingNo, H

如何查找hasPaid标志未设置为0的所有bookingNo

无法让它工作。我应该得到2-4-8号预订,HasPaid标志未设置为1

非常感谢

    if object_id('tempdb..#testFlag') is not null
        drop table #testFlag

    create table #testFlag (BookingNo int,  HasPaid bit)


    insert into #testFlag (BookingNo, HasPaid)
      select 1, 0 union ALL
      select 1, 1 union ALL
      select 2, 0 union ALL
      select 3, 0 union ALL
      select 3, 1 union ALL
      select 3, 0 union ALL
      select 4, 0 union ALL
      select 4, 0 union ALL
      select 4, 0 union ALL  
      select 5, 0 union ALL
      select 5, 1 union ALL
      select 6, 0 union ALL
      select 6, 1 union ALL
      select 7, 0 union ALL
      select 7, 1 union ALL
      select 8, 0 
如果你想在那个时候使用组

SELECT BookingNo FROM #testFlag
 GROUP BY BookingNo
HAVING MAX(cast(HasPaid as int)) = 0;

我想问题在于重复预订没有。 如果要选择所有已付款不为0的BookingNo,请尝试以下操作:

  select distinct BookingNo from #testFlag t1 where HasPaid != 0
  and not exists (select 1
  from #testFlag t2 where HasPaid = 0 and t2.BookingNo = t1.BookingNo
  )
  select distinct BookingNo from #testFlag t1 where HasPaid != 1
  and not exists (select 1
  from #testFlag t2 where HasPaid = 1 and t2.BookingNo = t1.BookingNo
  )
如果您想选择所有已付款的预订否非1,请尝试以下操作:

  select distinct BookingNo from #testFlag t1 where HasPaid != 0
  and not exists (select 1
  from #testFlag t2 where HasPaid = 0 and t2.BookingNo = t1.BookingNo
  )
  select distinct BookingNo from #testFlag t1 where HasPaid != 1
  and not exists (select 1
  from #testFlag t2 where HasPaid = 1 and t2.BookingNo = t1.BookingNo
  )
您可以将GROUP BY与基于案例的HAVING一起使用,如下所示

质疑

输出


出于好奇,这与仅仅从testFalg中选择BookNo有什么不同,testFalg支付了1。“那样似乎更简单。”HaukurHaf出于好奇,你为什么不测试一下呢。您更简单的方法是否返回预订2-4-8?不,我猜不是:-我只读了问题的第一句话,如何查找hasPaid标志未设置为0的所有预订否?。很抱歉。请注意,我们这里有两个表扫描。@我也喜欢使用except和intersect。只是指出在处理大量数据时效率不高。
BookingNo
2
4
8