2012-06-27 57 views
0

我在這裏失去我的觸摸。在過去,我會想出一個超級T-SQL查詢,我將如何創建此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

將所需的表列添加到您的子查詢SELECT語句中。 IE:(選擇max(t2.BatchId),結果來自table2 t2 ... – blearn

+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有一個錯誤,在註釋中正確注意到。我已將查詢更改爲正確的版本。

+2

已將您的左連接轉換爲您的語法的內連接add t.batchnumber = 1到ON子句而不是where子句http://wiki.lessthandot.com/index.php/WHERE_conditions_on_a_LEFT_JOIN – HLGEM

+0

oryol這個技巧並沒有我不能保證記錄已經被傳輸,所以結果表可能沒有相應的值。左連接是完美的。 –