2015-04-08 122 views
0

我有一個表,如下一個值:查詢匹配多個範圍

promo_code | minimum_order | discount 
------------+-------------------+------------- 
100   | 10    | 10% 
100   | 20    | 15% 
100   | 30    | 20% 
101   | 13    | 7% 
102   | 8    | 10% 
102   | 12    | 14% 

在另一個表我有量銷售,他們有資格的促銷

sales | promo_eligibility | record_id 
--------+-----------------------+------------- 
14  | 100     | 1000 
7  | 101     | 1001 
25  | 102     | 1002 

我需要獲得與銷量和促銷相對應的折扣...

如上例所示:

record_id | discount | Comments 
------------+---------------+-------------- 
1000  | 15%   | (bigger than 10 and lower than 20) 
1001  | 0%   | (did not reached the minimum) 
1002  | 14%   | 

閾值的數量可以變化從0到3

任何想法?

謝謝!

+0

什麼是*折扣*場...文本或數字的數據類型? – HansUp

+0

請解釋爲什麼* record_id * 1000分配了15%*折扣*而不是10%。 – HansUp

+0

@HansUp在評論中解釋說,14> 10,但14 <20? – PaulFrancis

回答

0

事情是這樣的:

select 
    r.record_id, 
    isnull(d.discount, '0%') 
from records r 
outer apply (
    select top 1 discount 
    from discounts d 
    where d.promo_code = r.promo_eligibility 
    and d.minimum_order <= r.sales) 
+1

注意我也會得到10%的爭議訂單......它不符合15%的折扣。 –