0

我在这里失去了联系。在过去,我会想出一个超级 T-SQL 查询,

选择 t1.Number, t1.TransactionType, t1.Description, t1.Vendor,
(Select max(t2.BatchId) From table2 t2
 其中 t1.Number=t2.Number 和 t1.TransactionType=t2.TransactionType
 按 t2.number,t2.transactiontype 分组)作为 BatchId
从表 1 t1

我需要 table2 中的第二列。列称为“结果”。

例子:

表格1:
编号、交易类型、描述、供应商
1、Type1、Test1、Vendor1
2、Type1、Test2、Vendor2
1、Type2、Test3、Vendor3
3、Type2、Test1、Vendor2

表2:
编号、交易类型、批次 ID、结果
1、类型1、12、错误1
1、类型1、4、错误2
1、Type2、8、成功
3、Type2、7、成功

想要的结果集:
Number、TransactionType、Description、Vendor、BatchId、Result
1、Type1、Test1、Vendor1、12、error2
2、Type1、Test2、Vendor2、null、null
1、Type2、Test3、Vendor3、8、成功
3、Type2、Test1、Vendor2、7、成功

发布的查询负责前 5 列。现在最后一列怎么样?

4

1 回答 1

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在评论中正确注意到了一个错误。我已将查询更改为正确的版本。

于 2012-06-27T17:12:13.933 回答