0

私はここで私の接触を失っています。昔はスーパー T-SQL クエリを思いついたのですが、

t1.Number、t1.TransactionType、t1.Description、t1.Vendor、
(max(t2.BatchId) を選択 table2 t2 から
 t1.Number=t2.Number および t1.TransactionType=t2.TransactionType の場合
 BatchId として t2.number,t2.transactiontype) でグループ化
テーブル 1 から t1

table2 の 2 番目の列が必要です。列は「結果」と呼ばれます。

例:

表1:
番号、取引の種類、説明、ベンダー
1、タイプ 1、テスト 1、ベンダー 1
2、タイプ 1、テスト 2、ベンダー 2
1、タイプ 2、テスト 3、ベンダー 3
3、タイプ 2、テスト 1、ベンダー 2

表 2:
番号、TransactionType、BatchId、結果
1、タイプ 1、12、エラー 1
1、タイプ 1、4、エラー 2
1、Type2、8、成功
3、Type2、7、成功

必要な結果セット:
番号、TransactionType、Description、Vendor、BatchId、Result
1、タイプ 1、テスト 1、ベンダー 1、12、エラー 2
2、Type1、Test2、Vendor2、null、null
1、Type2、Test3、Vendor3、8、成功
3、タイプ 2、テスト 1、ベンダー 2、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 に答える