首页 > 解决方案 > SQL - 加入更改日期

问题描述

一个星期以来,我一直在为此挠头。

考虑两张表 - 一张清点库存:

+------------+--------------+----------+-------------------+
| product_id | product_name |   date   | on_hand_inventory |
+------------+--------------+----------+-------------------+
|          1 | Product A    | 6/1/2019 |                37 |
|          1 | Product A    | 6/2/2019 |                36 |
|          1 | Product A    | 6/3/2019 |                35 |
|          1 | Product A    | 6/4/2019 |                40 |
|          1 | Product A    | 6/5/2019 |                42 |
+------------+--------------+----------+-------------------+

...以及另一个跟踪费用:

+------------+----------------+------------+------------+------------+
| product_id | cost_component | cost_value | start_date |  end_date  |
+------------+----------------+------------+------------+------------+
|          1 | FOB            |         15 | 1/1/2019   | 6/1/2019   |
|          1 | FOB            |       15.5 | 6/2/2019   | 6/3/2019   |
|          1 | FOB            |         16 | 6/4/2019   | 12/31/9999 |
+------------+----------------+------------+------------+------------+

成本表的布局让我抓狂。我需要加入这些表以保持现有库存的运行估值,而且我想不出 SQL 中的方法可以让我在成本表中选择适当的行。produt_id 上的联接不起作用,因为它会返回该项目的所有成本组件,无论它们是否适用于该日期。我觉得应该涉及一个CASE声明,但我不确定那会是什么样子。这是在 MSSQL 2016 中,物有所值。

标签: sqlsql-server

解决方案


If you want the most recent cost, you can use join:

select t.*, c.*
from inventory i join
     costs c
     on c.product_id = i.product_id and
        i.date between c.start_date and c.end_date;

推荐阅读