代码之家  ›  专栏  ›  技术社区  ›  Burt

在范围表上计算成本

  •  2
  • Burt  · 技术社区  · 12 年前

    我有两张桌子,与下面的桌子相似:

    ItemTable
    -----------------------------
    ItemId | NumberPurchased
    1      | 10
    2      | 90
    

    我需要根据下表计算订单的总成本,下表根据订单数量对每件商品的价格进行了浮动:

    PriceBands
    -----------------------------
    ScaleId | LowerLimit | UpperLimit | CostPerItem
    1       | 1          | 5          | 10
    2       | 6          | 10         | 9
    3       | 11         | 20         | 8
    ...
    

    我需要以某种方式计算出总成本,并将其加入第一张表(项目)。

    有人能帮忙吗?

    为了明确ItemId 1,计算如下:

    NumberPurchased = 10
    (5 * 10) + (5 * 9)  = 95
    

    捆扎带仅对超过上限的物品生效。

    2 回复  |  直到 12 年前
        1
  •  4
  •   Filipe Silva    12 年前

    如果你对每件商品都有相同的价格,那么这样的东西可能会奏效:

    SELECT i.itemID, i.NumberPurchased, i.NumberPurchased * p.costPerItem as "Cost"
    FROM itemTable i, PriceBands p
    WHERE i.NumberPurchased >= p.LowerLimit 
          AND i.NumberPurchased <= p.UpperLimit;
    

    sqlfiddle demo

    如果你想要不同的商品价格,你必须在priceBands中放入一个itemId,并在该itemId上加入两个表。


    要处理购买的每一层号码的增量成本,您可以执行以下操作:

    SELECT i.itemID, i.NumberPurchased, SUM((
          CASE 
            WHEN i.NumberPurchased > p.upperLimit
              THEN p.upperLimit
            ELSE i.NumberPurchased - p.LowerLimit + 1
            END
          ) * p.costPerItem) AS "Cost"
    FROM itemTable i, PriceBands p
    WHERE i.NumberPurchased > p.LowerLimit
    GROUP BY 1, 2
    

    这将遍历PriceBands表中的每一行,同时 i.NumberPurchased > p.LowerLimit ,边做边总结:

    • 乘 p.costPerItem 具有 p.upperLimit 虽然 i.NumberPurchased > p.upperLimit . (5 * 10);
    • 乘 每项费用 带i.NumberPurchase-p.lowerLimit + 1. (9 * 10-6 + 1 . This + 1 is to include the lowerLimit `number也是)。

    sqlfiddle demo

        2
  •  1
  •   pawel.panasewicz    12 年前

    如果PriceBands表中有外键,则查询将返回您询问的内容:

    select it.itemId, pb.costPerItem
    from ItemTable it, 
         PriceBands pb
    where it.itemId = pb.itemId
    and it.numberPurchased >= pb.LowerLimit
    and it.numberPurchased <= pb.upperLimit;