SQL Server 2008 - 从数字范围的数量中排除

时间:2012-10-11 01:21:08

标签: sql-server-2008 loops

我需要SQL脚本的帮助。

我有一个带有orders列的card_number表,我有另一个名为card_range的表,它为每个客户端存储card_number个范围,并带有一个列来标记它是否处于活动状态或不活跃。

当我从orders表中选择数据时,我想排除所有不活跃的card_number范围

EG。 orders

order_id   card_number
1          101
2          102
3          201
4          301

card_range表,有效0 =否,1 =是

start_card_number end_card_number active
101               199             0
201               299             1
301               399             0

所以我想从orders表中返回的唯一数据是

order_id card_number
3        201

我想弄清楚的脚本是通过card_range表循环...谢谢

1 个答案:

答案 0 :(得分:1)

假设卡片范围不重叠:

declare @orders as table ( order_id int, card_number int )
insert into @orders ( order_id, card_number ) values
  ( 1, 101 ), ( 2, 102 ), ( 3, 201 ), ( 4, 301 )

declare @card_range as table ( start_card_number int, end_card_number int, active bit )
insert into @card_range ( start_card_number, end_card_number, active ) values
  ( 101, 199, 0 ), ( 201, 299, 1 ), ( 301, 399, 0 )

select order_id, card_number
  from @orders as o inner join
    @card_range as cr on
      cr.start_card_number <= o.card_number and o.card_number <= cr.end_card_number and
      cr.active = 1