0

我需要有关 SQL 脚本的帮助。

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

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

例如。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

所以我想从订单表返回的唯一数据是

order_id card_number
3        201

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

4

1 回答 1

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
于 2012-10-11T01:28:28.413 回答