2012-10-11 69 views
0

我需要一個SQL腳本幫助範圍的數量排除。SQL Server 2008中 - 從數字

我有一個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 

所以我想從訂單表中返回的唯一數據是

order_id card_number 
3  201 

的腳本我想弄清楚的是循環直通的card_range表...感謝

回答

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