sql - 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 中,物有所值。
解决方案
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;
推荐阅读
- php - 从 foreach 循环中逐块创建数组
- go - 如何知道 goroutine 是否仍然存在?
- hyperledger-fabric - Hyperledger Fabric 区块链重组或分叉
- angular - Ionic3:找不到“object”类型的不同支持对象“[object Object]”。NgFor 仅支持绑定到 Iterables,例如 Arrays
- go - 编译器可以优化 defer 中的递归调用吗?
- javascript - 如何基于api调用遍历树/数组-Javascript
- reporting-services - RDL 为行和组列的组
- python - 将数据添加到 json/list(嵌套 json)但收到错误“unhashable type:'list'
- wordpress - Wordpress 垃圾邮件管理员帐户
- c# - 如何使用 IMAPI 异步写入 CD/DVD?