我有一个用户输入了客户费用,但没有将这些特定费用分配给合同。
所有费用均为135美元,并在特定日期输入。我需要从两个表中获取信息,t_ARLineItem(收费明细)和t_Owner(所有者项),我编写了以下代码来查找受影响的人:
SELECT charge.ARLineItemID, charge.ContractID, charge.Amount, charge.DueDate, charge.UserName, owner.OwnerID, owner.OwnerNumber, owner.FirstName, owner.LastName FROM t_ARLineItem charge
JOIN t_Owner owner
on charge.OwnerID = owner.OwnerID
WHERE charge.Amount = '135' AND charge.DueDate = '6/24/2019' AND charge.ContractID = '0' AND
charge.OwnerID IN ('OwnerID', 'OwnerID', ...)
这将返回以下(〜2,000):
ARLineItemID | ContractID | Amount | DueDate | UserName | OwnerID | FirstName | LastName
-------------|------------|--------|---------|----------|---------|-----------|--------
123 | 0 | 135.00 | 6/24/19 | User | 5 | Name | Name
124 | 0 | 135.00 | 6/24/19 | User | 8 | Name | Name
我需要将每个没有合同ID的费用分配给该所有者的最活跃合同。每个OwnerID可以有多个合同,我需要将费用设置为最新的活动合同。该合同表为t_Contract,其结构为:
ContractID | OwnerID | ContractNumber | ContractDate | ContractStatus
-----------|---------|----------------|--------------|----------------
100 | 5 | 100 | 2015-05-15 | Active
151 | 5 | 151 | 2017-11-29 | Inactive
165 | 5 | 165 | 2019-05-25 | Active
在此示例中,所有者ID 5将需要分配给合同165的费用ID 123。
ARLineItemID | ContractID | Amount | DueDate | UserName | OwnerID | FirstName | LastName
-------------|------------|--------|---------|----------|---------|-----------|--------
123 | 165 | 135.00 | 6/24/19 | User | 5 | Name | Name
编辑:在社区的帮助下,我已经走了很远,但我无法使它正常工作
UPDATE t_ARLineItem
SET ContractID = latestActiveContract.ContractID
FROM t_ARLineItem charge
JOIN t_Owner owner ON charge.OwnerID = owner.OwnerID
CROSS APPLY (
SELECT TOP 1 *
FROM t_Contract c
WHERE c.OwnerID = owner.OwnerID
AND c.ContractStatus = 'Active'
ORDER BY c.ContractDate DESC
) latestActiveContract
WHERE
charge.Amount = '135'
AND charge.DueDate = '6/24/2019'
AND charge.ContractID = '0'
AND charge.OwnerID = '16014'
答案 0 :(得分:1)
使用CROSS APPLY
和TOP 1
和ORDER BY
可以将费用与最新的有效合同相匹配:
UPDATE charge
SET charge.ContractID = latestActiveContract.ContractID
FROM t_ARLineItem charge
JOIN t_Owner owner ON charge.OwnerID = owner.OwnerID
CROSS APPLY (
SELECT TOP 1 *
FROM t_Contract c
WHERE c.OwnerID = owner.OwnerID
AND c.ContractStatus = 'Active'
ORDER BY c.ContractDate DESC
) latestActiveContract
WHERE
charge.Amount = '135'
AND charge.DueDate = '6/24/2019'
AND charge.ContractID = '0'
AND charge.OwnerID IN ('5', '8')