首页 > 解决方案 > 需要帮助将 ID 列与另一个 ID 列链接以进行插入

问题描述

我正在从存储过程生成数据集。ID我需要将来自不同数据库的列链接到我的数据集。从一个数据库到另一个数据库不是问题。问题是我在链接ID一个数据库而不是另一个数据库中的列时遇到问题。

两列之间有一个共同的 ID:CustomerEventID. 我知道这将是我的链接,但这是问题所在。这CustomerEventID是客户在一次遭遇中购买商品时的唯一 ID。

我需要引入的列更加离散。CustomerPurchaseID它为从遭遇战中购买的每件物品创建一个唯一的 ID ( )。但是,我只需要提取CustomerPurchaseID在那次遭遇中购买的最后一件物品。不幸的是,没有与CustomerPurchaseID.

它基本上就像CustomerEventID是客户收据CustomerPurchaseID的唯一 ID,而 是在该收据上购买的每件商品的唯一 ID。

CustomerPurchaseIDCustomerEventID(我只需要数据集中收据上的最后一项)中提取最后一项的最佳方法是什么?我将把我的存储过程与数据集(来自数据库 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

感谢您花时间阅读这堵文字墙。:)

例子

标签: sqlsql-server

解决方案


如果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

推荐阅读