Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to combine data from different tables using a query
    primarykey
    data
    text
    <p>I have a set of tables that look like what I have shown below.</p> <p>Could you let me know how I can achive the desired output ?</p> <pre><code>CREATE TABLE #ABC([Year] INT, [Month] INT,Customer Varchar(10), SalesofProductA INT); CREATE TABLE #DEF([Year] INT, [Month] INT,Customer Varchar(10), SalesofProductB INT); CREATE TABLE #GHI([Year] INT, [Month] INT,Customer Varchar(10), SalesofProductC INT); INSERT #ABC VALUES (2013,1,'PPP',1); INSERT #ABC VALUES (2013,1,'QQQ',2); INSERT #ABC VALUES (2013,2,'PPP',3); INSERT #DEF VALUES (2013,1,'QQQ',4); INSERT #DEF VALUES (2013,1,'RRR',5); INSERT #DEF VALUES (2013,2,'PPP',6); INSERT #GHI VALUES (2013,1,'QQQ',7); INSERT #GHI VALUES (2013,2,'RRR',8); INSERT #GHI VALUES (2013,3,'PPP',9); INSERT #GHI VALUES (2013,3,'QQQ',10); </code></pre> <p>I have a query currently that looks like this . @Month and @Year are supplied as parameters</p> <pre><code>SELECT -- select the sum for each year/month combination using a correlated subquery (each result from the main query causes another data retrieval operation to be run) (SELECT SUM(SalesofProductA) FROM #ABC WHERE [Year]=T.[Year] AND [Month]=T.[Month]) AS [Sum_SalesofProductA] ,(SELECT SUM(SalesofProductB) FROM #DEF WHERE [Year]=T.[Year] AND [Month]=T.[Month]) AS [Sum_SalesofProductB] ,(SELECT SUM(SalesofProductC) FROM #GHI WHERE [Year]=T.[Year] AND [Month]=T.[Month]) AS [Sum_SalesofProductC] FROM ( -- this selects a list of all possible dates. SELECT [Year],[Month] FROM #ABC where Year = @Year and Month = @Month UNION SELECT [Year],[Month] FROM #DEF where Year = @Year and Month = @Month UNION SELECT [Year],[Month] FROM #GHI where Year = @Year and Month = @Month ) AS T; </code></pre> <p>Right now I see an output like this : for a particular value of @Month and @Year</p> <pre><code> SalesofProductA, SalesofProductB, SalesofProductC </code></pre> <p>What I would like to see is :</p> <pre><code>[Customer],SalesofProductA, SalesofProductB, SalesofProductC </code></pre> <p>Does anyone know how it can be done ?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload