我有两个看起来像这样的表。一个具有“包装”数据,另一个具有“配方”数据。
Order# Lot# Pkg# Time
----------------------------
188688 PVB079 19 2:34
188688 PVB079 24 3:15
188688 PVB079 18 4:08
188688 PVB079 13 5:02
188688 PVB079 14 5:40
188688 PVB079 16 6:18
188688 PVB079 15 6:48
188688 PVB079 21 7:22
188688 PVB079 17 8:12
Order# Recipe Version Time
------------------------------
188688 EP01 1 2:35
188688 EP01 2 4:09
188688 EP01 3 6:49
我可以将它们联合在一起,并在时间戳之前对其进行排序,以获取类似于以下内容的内容...
Order# Lot# Pkg# Time Recipe Version
----------------------------------------------
188688 PVB079 19 2:34 -- --
188688 -- -- 2:35 EP01 1
188688 PVB079 24 3:15 -- --
188688 PVB079 18 4:08 -- --
188688 -- -- 4:09 EP01 2
188688 PVB079 13 5:02 -- --
188688 PVB079 14 5:40 -- --
188688 PVB079 16 6:18 -- --
188688 PVB079 15 6:48 -- --
188688 -- -- 6:49 EP01 3
188688 PVB079 21 7:22 -- --
188688 PVB079 17 8:12 -- --
但是,我希望将它们组合在一起,以便配方数据与其之前的1个软件包以及其后的其他软件包位于同一行。我理想的结果看起来像这样...
Order# Lot# Pkg# PkgTime Recipe Version RecipeTime
---------------------------------------------------------------
188688 PVB079 19 2:34 EP01 1 2:35
188688 PVB079 24 3:15 EP01 1 2:35
188688 PVB079 18 4:08 EP01 2 4:09
188688 PVB079 13 5:02 EP02 2 4:09
188688 PVB079 14 5:40 EP02 2 4:09
188688 PVB079 16 6:18 EP02 2 4:09
188688 PVB079 15 6:48 EP02 3 6:49
188688 PVB079 21 7:22 EP02 3 6:49
188688 PVB079 17 8:12 EP02 3 6:49
操作上,输入包装(时间戳),然后他们获得配方(时间戳)。但是有时候配方不会改变。因此,对于以下软件包,他们使用相同的配方,直到配方更改为止。
有可能吗?如何将这两个表合并在一起?
谢谢!
union
无关。您可以使用横向联接轻松完成此操作,在SQL Server中使用apply
:select p.*, r.*
from package p outer apply
(select top (1) r.*
from recipe r
where r.order# = p.order# and r.time > p.time
order by r.time asc
) r;
横向连接就像一个相关的子查询,可以返回多列和多行(尽管在这种情况下,它仅返回一行)。