title: how to sql query to get the right values
body: <p>I have about 24 tables (JanSales13 – DecSales14) with exact the same columns for each month.
  I want to be able to join each of these tables dynamically or alternatively. That is to dynamically choose the tables (eg.FebSales13 &amp; JulySales13 OR DecSales13 &amp; AprilSales14 ).
  First of all I need to <code>union</code> the chosen /selected tables.
  After the <code>union</code> operator combines these tables, I want to select some columns and then aggregate their transactional data.
  The logic: To be able to choose any two tables. The tables should then combine into one. After the <code>UNION</code> operator, get record of the union table</p>
  
  <p>That’s what I have so far. A dynamic  union table. The user should be able to  choose any table:</p>
  
  <pre><code>CREATE PROC spCombine
     @Table_Name  sysname,
     @Table_Name2  sysname
  AS
  BEGIN
    SET NOCOUNT OFF;
  
  DECLARE @Dynamictbl nvarchar(MAX)
  
  SET @Dynamictbl = 
  N'SELECT * FROM ' + @Table_Name +
  ' UNION
  SELECT * FROM ' + @Table_Name2
  
  EXECUTE sp_executesql @Dynamictbl
  
  END
  </code></pre>
  
  <p>This roughly query should be executed after the two tables combine</p>
  
  <pre><code>    SELECT
   Product, Description,
   Sum(A_Sales ) AS [A_salesFeb],
   Sum(A_Sales ) AS [A_salesMay],
   Sum(A_Sales ) AS [B_salesFeb],
   Sum(A_Sales ) AS [B_salesMay],
   Sum(A_Sales ) AS [C_salesFeb],
   Sum(A_Sales ) AS [C_salesMay],
  FROM ……
  GROUP BY Product, Description
  </code></pre>
  
  <p>So my expectation is if I execute the store procedure, the below three steps take place</p>
  
  <pre><code>EXEC spCombine @Table_Name =’ FebSales13’, @Table_Name2=’ MaySales13’
  </code></pre>
  
  <ol>
  <li>Choose any two tables</li>
  <li>Combine them together</li>
  <li>Results from main query</li>
  </ol>
  
  <p>Graphical image:
  <img src="https://i.stack.imgur.com/y7aj8.png" alt="enter image description here"></p>