选择两个不同表中的最近帖子(SQL)

时间:2014-08-08 09:25:10

标签: sql-server tsql join

我有两个表,Expense和EditedExpense。我有这两个表,因为当您想要在Expense中编辑帖子时,它会在EditedExpense中创建一个新帖子。所以你总是在费用表中有原始帖子。您只能更改原始帖子(费用表)。如果更改Expnese三次,您将找到三个具有相同ExpenseId的EditedExpense(不同的列值和DateCreated)。现在我想选择所有重新开支。 Resent exepense我的意思是如果Expense有一个或几个EditedExpnes,你选择最近的EditedExpense,否则选择原始Expense。 Espense表:

ExpenseId, DateCreated, .... ReceiptFilePath

和EditedExpense表:

EditedExpenseId, ExpenseId, DateCreated, .... ReceiptFilePath

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT e.ExpenseId, e.DateCreated, e....., e.ReceiptFilePath,
    X.EditedExpenseId AS EditedExpenseId_, X.ExpenseId AS ExpenseId_, X.DateCreated AS DateCreated_, 
    X..... AS .....,  X.ReceiptFilePath AS ReceiptFilePath_
FROM Espense AS e
    OUTER APPLY
    (SELECT TOP 1 ee.EditedExpenseId, ee.ExpenseId, ee.DateCreated, ee.....,  ee.ReceiptFilePath
        FROM EditedExpense AS ee
        WHERE ee.ExpenseId = e.ExpenseId
        ORDER BY ee.DateCreated DESC, ee.EditedExpenseId DESC) AS X