2015-06-23 28 views
0

我已經在這個表我已經報名參加各量相對優惠SQL - 找到正確的價值

Amount Discount 
500  5% 
1000  10% 
1200  11% 
2100  15% 

ECC了這個問題

...

在另一個表我已經得到了訂單的總價格,例如2000我如何找到這個訂單的正確折扣?在這種情況下,11%是因爲2100> 2000?

+1

哪個數據庫(Oracle,mySql,sql Server ...)? –

+0

哦,我忘了說,我正在使用SQL服務器 – Bifunk

回答

0
select discount 
    from tq84_discount 
where amount = (
    select max(amount) 
    from tq84_discount 
    where amount <= 2000 
); 

測試數據:

create table tq84_discount (
    amount number, 
    discount number 
); 

insert into tq84_discount values ( 0, 0); 
insert into tq84_discount values (500, 5); 
insert into tq84_discount values (100, 10); 
insert into tq84_discount values (1200, 11); 
insert into tq84_discount values (2100, 15); 
+0

非常感謝!!!!!你能幫我解決這個問題嗎? http://stackoverflow.com/questions/30968178/sql-recursion-statement-trigger/30984262#30984262非常感謝您的合作 – Bifunk

1

隨着top

select top 1 Discount 
from Discounts 
where Amount <= 2000 
order by Amount desc 
0
select top 1 Discount 
from Discounts 
where Amount < GrossPrice 
orderby Amount desc 

這個簡單的查詢工作。 GrossPrice是其中具有來自其他表的值的變量。 2000年在這種情況下。