【问题标题】:SQL - find the correct valueSQL - 找到正确的值
【发布时间】:2015-06-23 18:48:43
【问题描述】:

我遇到了这个问题

在此表中,我为每个金额注册了相对折扣

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

ecc...

在另一个表中,我得到了订单的总价,例如 2000,我如何才能找到该订单的正确折扣?在那种情况下 11% 因为 2100 > 2000 ?

【问题讨论】:

  • 哪个数据库(Oracle、mySql、sql Server...)?
  • 哦,我忘了说了,我用的是sql server

标签: sql sql-server between


【解决方案1】:

top:

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

【讨论】:

    【解决方案2】:
    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);
    

    【讨论】:

    【解决方案3】:
    select top 1 Discount
    from Discounts
    where Amount < GrossPrice
    orderby Amount desc
    

    这个简单的查询有效。 GrossPrice 是它具有来自其他表的值的变量。在这种情况下是 2000 年。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多