我需要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
表循环...谢谢
答案 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