How to left join on groups of data I would like to know how to left join columns for each group of data that is return in a set of data. The template needs to fill in the blanks for each group where there are missing records. Groups 1 and 2 are part of a single query and need to be part of the same result set.

TEMPLATE

Name          Num     
------------------------------------
Apples        10      
Bananas       20
Oranges       15
Pineapple     5
Grapes        30
Chips         50
Chocolate     6   


GROUP 1

Name          Num         Group
------------------------------------
Grapes        3    --     1
Chips         17   --     1


GROUP 2

Name          Num         Group
------------------------------------
Bananas       30   --     2
Oranges       10   --     2


NEW GROUP 1     

Name          Num         Group
------------------------------------
Apples        10          1     &lt;-- from template
Bananas       20          1     &lt;-- from template
Oranges       15          1     &lt;-- from template
Pineapple     5           1     &lt;-- from template
Grapes        3           1     &lt;-- same
Chips         17          1     &lt;-- same
Chocolate     6           1     &lt;-- from template


NEW GROUP 2

Name          Num         Group
------------------------------------
Apples        10          2     &lt;-- from template
Bananas       30          2     &lt;-- same
Oranges       10          2     &lt;-- same
Pineapple     5           2     &lt;-- from template
Grapes        30          2     &lt;-- from template
Chips         50          2     &lt;-- from template
Chocolate     6           2     &lt;-- from template


Groups 1 and 2 are stored in different tables. The number of groups is not limited to two. The algorithm is, basically, "return template but overwrite template's num with group's num where it is given." The result needs to be a single result set.
New Group1:

SELECT
   Name                  AS Name,
   ISNULL(g.Num,t.Num)   AS Num,
   '1'                   AS Group
FROM Template t
LEFT JOIN Group1 g ON t.Name=G.Name


New Group2:

SELECT
   Name                  AS Name,
   ISNULL(g.Num,t.Num)   AS Num,
   '2'                   AS Group
FROM Template t
LEFT JOIN Group2 g ON t.Name=G.Name


The ISNULL is comparable to the COALESCE function, but simpler to type, without breaking fingers 


  It needs to be a single result set since the numbers of groups is not limited to two


If your groups are in table Group, a single query would be:

SELECT
   Name                  AS Name,
   ISNULL(g.Num,t.Num)   AS Num,
   g.Group               AS Group
FROM Template t
LEFT JOIN Group g ON t.Name=G.Name