我有一个更新查询,用于运行最终标量值基于派生查询的位置。我需要确保在最外层的查询中更新正确的行。如何从RxTransactionID上的DERIVED2查询加入到此示例中的最外层查询?
注意:不允许使用此WHERE子句中的“A.RxTransactionID”。 WHERE Fact.Adherence.RxTransactionId = A.RxTransactionID
UPDATE Fact.Adherence SET Fact.Adherence.LAST_MPR = (
SELECT LAST_MPR FROM
(
SELECT
DERIVED1.IRXLocationId, DERIVED1.RxNumber, DERIVED1.RefillNumber, DERIVED1.RxTransactionID, DERIVED1.ClientId, DERIVED1.CompletedDate, DERIVED1.NextCompletedDate,
LAST_MPR = NULLIF(CAST(CAST(COALESCE(DaysSupply, 0) as decimal) / NULLIF(CAST(COALESCE(DATEDIFF(DAY, DERIVED1.CompletedDate, DERIVED1.NextCompletedDate), 0) as decimal), 0)as decimal(12,4)), 0)
FROM
(SELECT
[CompletedDate] As [CompletedDate],
NextCompletedDate = (SELECT -- Will be the second most recent complete date.
TOP 1 AA.[CompletedDate] FROM Fact.RxTransaction AA WHERE AA.RxId = C.RxId AND COALESCE(A.RefillNumber + 1,0) = AA.RefillNumber AND AA.RxID = C.RxID),
A.RxNumber, [DaysSupply], [RefillNumber], C.[RxID], A.RxTransactionID, A.ClientId, A.IRXLocationId
FROM [Fact].[Adherence] A
INNER JOIN Dimension.RX C on A.RxId = C.RxId
WHERE A.CompletedDate > DATEADD(MONTH, -6, GETDATE())
) DERIVED1
ORDER BY IRXLocationId, RxNumber, RefillNumber desc) DERIVEDA
)
WHERE Fact.Adherence.RxTransactionId = A.RxTransactionID
答案 0 :(得分:0)
如果将派生值和查找键放入Fact.Adherence到临时表中,则可以对这两个表的连接执行更新语句。
这里有一个关于如何进行更新加入的好例子:Update Join Example