我在这里失去了联系。在过去,我会想出一个超级T-SQL查询,
Select t1.Number, t1.TransactionType, t1.Description, t1.Vendor, (Select max(t2.BatchId) From table2 t2 Where t1.Number=t2.Number and t1.TransactionType=t2.TransactionType Group By t2.number,t2.transactiontype) As BatchId From table1 t1
我需要table2中的第二列。列称为“结果”。
示例:
table1: Number, TransactionType, Description, Vendor 1, Type1, Test1, Vendor1 2, Type1, Test2, Vendor2 1, Type2, Test3, Vendor3 3, Type2, Test1, Vendor2 table2: Number, TransactionType, BatchId, Result 1, Type1, 12, error1 1, Type1, 4, error2 1, Type2, 8, success 3, Type2, 7, success wanted ResultSet: Number, TransactionType, Description, Vendor, BatchId, Result 1, Type1, Test1, Vendor1, 12, error2 2, Type1, Test2, Vendor2, null, null 1, Type2, Test3, Vendor3, 8,success 3, Type2, Test1, Vendor2, 7,success
发布的查询负责前5列。那最后一栏怎么样?
答案 0 :(得分:0)
select t1.Number, t1.TransactionType, t1.Description, t1.Vendor, t2.BatchId, t2.Result
from table1 t1
left join
(
select t2.TransactionType, t2.number, t2.Result, t2.BatchId,
row_number() over (partition by t2.number, t2.TransactionType order by t2.BatchId desc) as BatchNumber
from table2 t2
) t2 on t1.Number = t2.Number
and t1.TransactionType = t2.TransactionType
and t2.BatchNumber = 1
如果你可以确定t1中的每一行都有t2中的相关行,那么用内连接替换左连接会更好。
UPD 在评论中发现了错误。我已将查询更改为正确的版本。