• A full optimization will take a few minutes, but the main problem seems to be a missing index, something like:

    CREATE UNIQUE NONCLUSTERED INDEX [UQ dbo.TransactionDetail TransactionId (AccountId, Direction, Amount)]

    ON [dbo].[TransactionDetail] (TransactionId ASC)

    INCLUDE (AccountId, Direction, Amount)

    WITH (SORT_IN_TEMPDB = ON, MAXDOP = 1, ONLINE = OFF);

    and change the temporary table creation to:

    CREATE TABLE #Accounts (AccountNumber nvarchar(20) PRIMARY KEY);