Home Forums SQL Server 2005 SQL Server Newbies LEFT JOIN not returning anticipated results from Left table in query RE: LEFT JOIN not returning anticipated results from Left table in query

  • sjerromeharris (3/24/2014)


    Thanks for your post, and the link to the article.

    I've tried your suggestion, but its not making much difference to the results that are being returned. I'm expecting around 58 rows but I'm only getting around 40.

    Is there anything else I can try? (I've added a couple of extra columns to the query)

    SELECT

    Users.Department as Dept,

    CaseTypes.Description as Case_Type,

    Users.Code as FE,

    COUNT(Matters.FeeEarnerRef) as No_of_Matters,

    ISNULL(SUM(Usr_Int1.Estimated_total_fee),0) as Fee_Estimate

    FROM

    ((Users LEFT JOIN Matters ON Users.Code = Matters.FeeEarnerRef and (Matters.Created >= GetDate() - 7 AND Matters.Created <= GetDate())

    INNER JOIN CaseTypes ON Matters.CaseTypeRef = CaseTypes.Code)

    INNER JOIN Usr_Int1 ON (Matters.Number = Usr_Int1.MatterNo) AND (Matters.EntityRef = Usr_Int1.EntityRef))

    WHERE

    ((usertyperef =1) or (usertyperef = 2))

    GROUP BY

    users.code, usertyperef, users.department, casetypes.description, users.department, casetyperef, users.feeearner

    ORDER BY

    users.department, casetyperef, users.code;

    Thank you

    It is because you have an INNER join to Usr_Int1 using a value from Matters. This basically converts this to an INNER join on Matters. Change that to a LEFT and I think you are pretty close.

    SELECT Users.Code AS FE

    ,COUNT(Matters.FeeEarnerRef) AS No_of_Matters

    ,ISNULL(SUM(Usr_Int1.Estimated_total_fee), 0) AS Fee_Estimate

    FROM Users

    LEFT JOIN Matters ON Users.Code = Matters.FeeEarnerRef

    AND created > '2014-03-16'

    LEFT JOIN Usr_Int1 ON (Matters.Number = Usr_Int1.MatterNo)

    AND (Matters.EntityRef = Usr_Int1.EntityRef)

    WHERE (users.feeearner = 1)

    AND usertyperef <> 7

    GROUP BY code

    ,usertyperef

    ORDER BY code

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/