在同一行中添加列字段值?

时间:2018-11-16 21:36:38

标签: sql database db2

我正在db2上使用SQL。

运输表:

 +--------+------+
 | Weight | Cost |
 +--------+------+
 |      2 |    5 |
 |      5 |   10 | 
 |     10 |   15 | 
 |     30 |   45 |  
 |     50 |   80 |  
 +--------+------+

项目表:

  +---------+--------+
  | Item ID | Weight |  
  +---------+--------+
  |       1 |     34 |  
  |       2 |      4 | 
  |       3 |      9 |    
  |       4 |      5 |  
  |       5 |     16 |    
  +---------+--------+

我想使用重量将适当的运输费用与物料相关联。因此,如果该商品的重量与等于或大于该重量的下一个重量相关联。

我希望我的结果表出现在INNER JOIN之后,一切都是:

+---------+-------------+-----------------+---------------+
| Item ID | Item Weight | Shipping Weight | Shipping Cost | 
+---------+-------------+-----------------+---------------+
|       1 |          34 |              50 |            80 |   
|       2 |           4 |               5 |            10 |  
|       3 |           9 |              10 |            15 |  
|       4 |           5 |               5 |            10 |  
|       5 |          16 |              30 |            45 | 
+---------+-------------+-----------------+---------------+

我无法弄清楚如何将运输重量与物品重量相关联。一旦这样做,我就可以承担运费。

我尝试过使用“ WHERE> =运输重量”,但这给了我所有的可能性,而我只想要最好的,等于或次于最大的。我不太善于解释这一点,但我希望您通过查看所需的结果表来理解我的意思。

谢谢!

1 个答案:

答案 0 :(得分:2)

Well, you can use a correlated subquery to get the weight and then a join to get the associated cost:

select i.*, s.*
from (select i.*,
             (select min(s.weight)
              from shipping s
              where s.weight >= i.weight
             ) as shipping_weight
      from items i
     ) i join
     shipping s
     on i.shipping_weight = s.weight;

Perhaps a funner method uses window functions:

select i.*, s.*
from items i join
     (select s.*, lag(weight) over (order by weight) as prev_weight
      from shipping s
     ) s
     on i.weight <= s.weight and
        (i.weight > prev_weight or prev_weight is null)
相关问题