Syntax problem joining to select statements

  • I have a DB table that contains a branchNumber and a dateEntered field among others.

    I want to retrieve a unique record for each branchNumber with the latest dateEntered date. I have the sql below.

    The first selection chooses fields from the joined selections.

    The second selection gets the unique branchNumbers with the latest dateEntered from the table. (tested good)

    which is left joined with

    the third selection which gets all the records from the table. (tested good)

    On allRecs.branchNumber and allRecs.dateEntered = distinctRecs.branchNumber and distinctRecs.dateEntered

    My query below is giving me these syntax errors. Does anyone have some advise?

    Msg 156, Level 15, State 1, Line 8

    Incorrect syntax near the keyword 'SELECT'.

    Msg 156, Level 15, State 1, Line 12

    Incorrect syntax near the keyword 'LEFT'.

    Msg 156, Level 15, State 1, Line 19

    Incorrect syntax near the keyword 'ON'.

    SELECT distinctRecs.branchNumber ,

    distinctRecs.dateEntered ,

    allRecs.preparedByFirst ,

    allRecs.approvedByFirst ,

    allRecs.preparedByLast ,

    allRecs.approvedBylast

    FROM

    SELECT max([dateEntered]) ,

    [branchNumber]

    FROM [VaultRecap].[dbo].[cashMovement] distinctRecs

    GROUP BY [branchNumber]

    LEFT JOIN

    SELECT [preparedByFirst] ,

    [approvedByFirst] ,

    [preparedByLast] ,

    [approvedByLast] ,

    [branchNumber] ,

    [dateEntered]

    FROM [VaultRecap].[dbo].[cashMovement] allRecs

    ON allRecs.dateEntered = distinctRecs.dateEntered

    AND allRecs.branchNumber = distinctRecs.branchNumber

    ORDER BY distinctRecs.branchNumber

  • Put parenthesis aroud the subqueries that will form your datasets.

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • Thank you for the input. I got it working now with this code.

    SELECT distinctRecs.branchNumber ,

    distinctRecs.dateEntered ,

    allRecs.preparedByFirst ,

    allRecs.approvedByFirst ,

    allRecs.preparedByLast ,

    allRecs.approvedBylast

    FROM

    (SELECT max([dateEntered]) as dateEntered ,

    [branchNumber]

    FROM [VaultRecap].[dbo].[cashMovement]

    GROUP BY [branchNumber]) distinctRecs

    LEFT JOIN

    (SELECT [preparedByFirst] ,

    [approvedByFirst] ,

    [preparedByLast] ,

    [approvedByLast] ,

    [branchNumber] ,

    [dateEntered]

    FROM [VaultRecap].[dbo].[cashMovement]) allRecs

    ON allRecs.dateEntered = distinctRecs.dateEntered

    AND allRecs.branchNumber = distinctRecs.branchNumber

    ORDER BY distinctRecs.branchNumber

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply