Wednesday 5 September 2018

Join - Left join with a filter on both tables, return zero if no match

I'm trying to calculate the difference between 2 values on 2 related tables.

    SELECT        a.[Batch No_], b.[Lot No_], b.[Open], a.[Current Stock], b.Amount, a.[Batch Value]
    FROM            [sb] AS a LEFT OUTER JOIN
                     [ile] AS b ON a.[Batch No_] = b.[Lot No_]
    WHERE        (a.[Current Stock] = 1) AND (b.[Open] = 1)

I want all records from sb(a) to be returned, where Current Stock = 1. I want all matching records from ile(b) to be returned, where Open = 1.
The problem is, If there is no matching record, i still want the sb(a) fields to be returned, with b.Amount set to 0.
There are multiple records where b.Open = 0, which must not be returned.
How do I go about this? I saw a solution involving COALESCE, but I couldn't get it working
Thanks

Since you want A no matter what, do not include any hard conditions on B in your where clause. All columns of B will be NULL for rows not matched by A. Move those conditions to your JOIN. Like this:
SELECT        a.[Batch No_],
              b.[Lot No_],
              b.[Open],
              a.[Current Stock],
              isnull(b.Amount,0)
              a.[Batch Value]
FROM            [sb] AS a LEFT OUTER JOIN
                [ile] AS b ON a.[Batch No_] = b.[Lot No_]
                and 1 = b.[Open]
WHERE        (a.[Current Stock] = 1)

Then you can use ISNULL or COALESCE in your SELECT clause to force b.amount to be 0 when B is not matched.

0 comments:

Post a Comment