sql - 需要帮助将 ID 列与另一个 ID 列链接以进行插入
问题描述
我正在从存储过程生成数据集。ID
我需要将来自不同数据库的列链接到我的数据集。从一个数据库到另一个数据库不是问题。问题是我在链接ID
一个数据库而不是另一个数据库中的列时遇到问题。
两列之间有一个共同的 ID:CustomerEventID
. 我知道这将是我的链接,但这是问题所在。这CustomerEventID
是客户在一次遭遇中购买商品时的唯一 ID。
我需要引入的列更加离散。CustomerPurchaseID
它为从遭遇战中购买的每件物品创建一个唯一的 ID ( )。但是,我只需要提取CustomerPurchaseID
在那次遭遇中购买的最后一件物品。不幸的是,没有与CustomerPurchaseID
.
它基本上就像CustomerEventID
是客户收据CustomerPurchaseID
的唯一 ID,而 是在该收据上购买的每件商品的唯一 ID。
CustomerPurchaseID
从CustomerEventID
(我只需要数据集中收据上的最后一项)中提取最后一项的最佳方法是什么?我将把我的存储过程与数据集(来自数据库 A)一起使用,使用 SSIS 包将数据集放入数据库 B 上的表中,然后将其插入CustomerPurchaseID
到该表中。
我不确定它是否有帮助,但这是来自存储过程的查询,它将被发送到另一个数据库(该过程将每 2 周运行一次以将其发送到数据库 B):
SELECT
ce.CustomerEventID,
ce.CustomerName,
ce.CustomerPhone,
ce.CustomerEventDate
FROM
CustomerEvent ce
WHERE
DATEDIFF(d, ce.CustomerEventDate, GETDATE()) < 14
感谢您花时间阅读这堵文字墙。:)
解决方案
如果CustomerPurchaseID
字段正在增加(如您所述),那么您可以Order by Desc
在拿起线路时在该字段上进行操作。这可以使用父查询中的子查询来完成,Outer Apply
或者Cross Apply
如果您需要CustomerPurchase
表中的所有字段,也可以这样做。检查下面的例子。
declare @customerEvent table(CustomerEventID int not null primary key identity
, EventDate datetime)
declare @customerPurchase table(CustomerPurchaseID int not null primary key identity
, CustomerEventID int, ItemID varchar(100))
insert into @customerEvent(EventDate)
values ('2018-01-01'), ('2018-01-02'), ('2018-01-03'), ('2018-01-04')
insert into @customerPurchase(CustomerEventID, ItemID)
values (1, 1), (1, 2), (1, 3)
, (2, 3), (2, 4), (2, 10)
, (3, 1), (3, 2)
, (4, 1)
-- if you want all the fields from CustomerPurchase Table
select e.CustomerEventID
, op.CustomerPurchaseID
from @customerEvent as e
outer apply (select top 1 p.* from @customerPurchase as p where p.CustomerEventID = e.CustomerEventID
order by CustomerPurchaseID desc) as op
-- if you want only the last CustomerPurchaseID from CustomerPurchase table
select e.CustomerEventID
, (select top 1 CustomerPurchaseID from @customerPurchase as p where p.CustomerEventID = e.CustomerEventID
order by CustomerPurchaseID desc)
as LastCustomerPurchaseID
from @customerEvent as e
推荐阅读
- angular - Angular 应用程序在更改时停止重新加载
- javascript - 使用 Javascript 在另一个选项卡或窗口中提交表单
- javascript - 即使我与页面交互也无法录制音频
- javascript - 静态文件不在一个模板上加载,而是在另一个模板上加载
- javascript - Vue 3 refs 在渲染函数中未定义
- android - Drawable在Android App中不显示角落
- curl - 为什么当我尝试从 LinkedIn 检索个人的电子邮件地址时 curl 不起作用
- ssh - scp 显示权限被拒绝但 ssh 正在工作
- java - 如何在构造函数上应用方法
- vba - 有没有办法在 PowerPoint VBA 中使用形状的 ID 来确定它的颜色?